All threads / Rails has_one, belongs_to, join_table and nested form

Ask A Question


You’re not receiving notifications from this thread.

Rails has_one, belongs_to, join_table and nested form

Lee Terng Gio asked in Rails

I'm creating a User, Role and UserRole. A user can create a list of roles, and from the new user form, there is a nested form which populate a list of roles created, then the user able to select a role and associated with the new user. I'm able to create a list of roles, but facing problem when creating a nested form in the new user view file.

Here are the models, kindly advise me if relationships are correct.

class User < ApplicationRecord
  has_one :user_role
  has_one :role, through: :user_role
class Role < ApplicationRecord
  has_many :user_role
  has_many :user, through: :user_role
class UserRole < ApplicationRecord
  belongs_to :user
  belongs_to :role

User controller. I'm not sure if my controller is correct:

def new
  @user = User.find_by_id(params[:id])
    @user =
  @user = @current_user.build_user_role

def create
    @user = User.find_by_id(params[:id])                
    @user = @current_user.account.users.create_with_password(user_params)
  redirect_to users_path
  render 'new'

def user_params
  params.require(:user).permit(:id, :email, :password, :password_confirmation, :admin, :owner, user_role_attributes: [:user_id, :role_id])


Below is new user form:

<%= form_for(@user, remote: true) do |f| %>

<%= f.text_field :email, class: "form-control", autofocus: true, autocomplete: "off" %>
<%= f.check_box :admin, class:"checkbox" %>
<%= f.check_box :owner, class:"checkbox" %>

<%= f.fields_for :user_role do |ff| %>
<!-- I don't know how to create a select dropdown to populate a list of roles that have been created -->
<% end %>             

<%= f.button "Create",  class: "btn btn-success" %>

<% end %>
Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 48,387+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2021 GoRails, LLC. All rights reserved.