嵌套的属性不保存在连接表中USER_ID [英] nested attributes not saving the user_id in join table
问题描述
系统管理员主要控制器:
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
邀请型号
belongs_to :admin
belongs_to :user
管理模型
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
用户型号
has_many :invitations
has_many :user_admin_relationships
has_many :admins, :through => :user_admin_relationships
我的表格嵌套形式,它工作正常保存每个表单字段和项目,如 created_at
和 sent_at
。 但是,它不保存 USER_ID
(user_admin连接表)和 SENDER_ID
(邀请表)。
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.
的东西,不工作:
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
我已经尝试了一堆其他的不同排列的为好。是不是有什么毛病我联想?我怎样才能更新 SENDER_ID
在丰富的邀请表和 USER_ID
加入user_admin_relationship表?我知道我可以通过做一个 hidden_field
,但听说了,我不想这样做,这不是安全的。
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.
推荐答案
使用:
params[:invitation].merge!(:sender_id => current_user.id)
注意 =>
,而你只是有 =
。然而,在你的创建
动作,要添加到 PARAMS [:邀请]
,但你是不是保存任何地方,所以它只是迷路。你可能想使用:
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]
此外,您存储 SENDER_ID
,但你没有什么要告诉你的用户模型来寻找 SENDER_ID
作为外键。默认情况下它会寻找 USER_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'
和两种:
Invitation: belongs_to :sender, :class_name => "User" # recommended
# or
Invitation: belongs_to :user, :foreign_key => 'sender_id'
这篇关于嵌套的属性不保存在连接表中USER_ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!