nested attributes not saving the user_id in join table

跟風遠走 提交于 2019-12-25 00:32:35

问题


Admin Main controller:

def new
  @admin = Admin.new
  @invitation = @admin.invitations.build
  @admi.user_admin_relationships.build
end

def create
  params[:invitation][:sender_id] = current_user.id
  @admin = Admin.new(params[:admin])
  if @admin.save
    redirect_to root_path
  else
    render 'new'
  end
end

Invitation Model

belongs_to :admin
belongs_to :user

Admin Model

has_many :invitations
has_many :user_admin_relationships
has_many :users, :through => :user_admin_relationships

accepts_nested_attributes_for :invitations
accepts_nested_attributes_for :user_admin_relationships, :allow_destroy => true

User Model

has_many :invitations
has_many :user_admin_relationships
has_many :admins, :through => :user_admin_relationships

My forms are nested forms and it works fine saving the fields per the form and items such as created_at and sent_at. However, it does not save the user_id (user_admin join table) and sender_id (invitation table).

I tried adding different permutations to the admin controller, but nothing is working.

Things that does not work:

params[:invitation][:sender_id] = current_user.id

This gives me I have a nil object when I didn't expect it error.

params[:invitation].merge!(:sender_id = current_user.id)

This give me a "wrong syntax error"

@admin.invitations.build(params[:invitation][:sender_id]) = current_user.id

This gives me unexpected "=" and "expecting keyword end" error

I have tried a bunch of other different permutations as well. Is there something wrong with my associations? How can I update the sender_id in the invitation table and the user_id in the rich join user_admin_relationship table? I know I can do it via a hidden_field, but heard it's not safe so I don't want to do that.


回答1:


Use:

params[:invitation].merge!(:sender_id => current_user.id)

Notice the =>, whereas you just has =. However, in your create action, you are adding that to params[:invitation], but then you aren't saving that anywhere, so it's just getting lost. You probably want to use:

params[:admin][:invitations_attributes][:sender_id]

Also, you are storing sender_id but you don't have anything to tell your User model to look for sender_id as the foreign key. By default it will look for user_id. You have to add this:

User: has_many :invitations, :foreign_key => 'sender_id'

and either:

Invitation: belongs_to :sender, :class_name => "User" # recommended
# or 
Invitation: belongs_to :user, :foreign_key => 'sender_id'


来源:https://stackoverflow.com/questions/7740873/nested-attributes-not-saving-the-user-id-in-join-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!