Ask A Question

Notifications

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
end
class Role < ApplicationRecord
  has_many :user_role
  has_many :user, through: :user_role
end
class UserRole < ApplicationRecord
  belongs_to :user
  belongs_to :role
end

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

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

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

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

end

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 %>
Reply
Join the discussion
Create an account Log in

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

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

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