Attributes passed to .build() dont show up in the query
Hope your all enjoying your hollydays.
Ive run into a pretty funny problem when trying to insert rows into a really really simple database table.
The basic idea is pretty simple. The user selects one/multiple users in a multiselect which are supposed to be added to a group.This piece of code will insert a row into the user_group_relationships table, but the users id always
@group = Group.find(params[:group_id])
params[:newMember][:users].each do |uid|
# For debugging purposes.
puts 'Uid:'+uid
@rel = @group.user_group_开发者_C百科relationships.build( :user_id => uid.to_i )
@rel.save
end
The user id always gets inserted as null even though it is clearly there. You can see the uid in this example is 5, so it should work.
Uid:5
... SQL (0.3ms) INSERT INTO "user_group_relationships" ("created_at", "group_id", "updated_at", "user_id") VALUES ('2010-12-27 14:03:24.331303', 2, '2010-12-27 14:03:24.331303', NULL)
Any ideas why this fails?
Looks like user_id
is not attr_accessible
in the UserGroupRelationship
model.
You might also want to check this it may be relevant.
I think @zabba's answer is probably the one you need to look for but i would suggest a couple of extra things here.
Your "Group" and "User" models are connected to each other thru the "UserGroup" model it seems. You would have relationship
class Group < ActiveRecord::Base
has_many :user_group_relationships
has_many :users, :through => :user_group_relationships
end
class UserGroupRelationship < ActiveRecord::Base
belongs_to :group
belongs_to :user
end
In your controller
# Find the group
@group = Group.find(params[:group_id])
# For each user id, find the user and add the user_group_relationship
params[:newMember][:users].each{|u| @group.users << User.find(u) }
Read up Rails Documentation on associations and the methods generated automatically for you when associations are defined. More often than not, working with association is easier than you might think! I discover new APIs in Rails constantly! :) Good Luck!
精彩评论