rails storing id's from reference table
When I submit a text field into user_items
I want it to take the ID
of that item from master_list_items
and place it into the master_list_items_id
column under user_items
I have added master_list_items.rb -- but I'm not sure of the relationship to add..
Any suggestions?
master_list_items
+----------------------+----+
| name | id |
+----------------------+----+
| Item A | 1 |
| Item B 开发者_运维技巧| 2 |
| Item C | 3 |
+----------------------+----+
user_items
+---- +----------+----------------------+
| uid | item | master_list_item_id |
+-----+----------+----------------------+
| 2 | Item A | NULL |
| 7 | Item C | NULL |
| 9 | Item C | NULL |
+-----+----------+----------------------+
I'm going to guess your models are done like this:
class MasterListItem < ActiveRecord::Base
has_many :user_items
end
class UserItem < ActiveRecord::Base
belongs_to :master_list_item
end
To implement what you're looking for the solution would probably be like this:
master_list_item = MasterListItem.create( :name => "Item 1" )
user_item = master_list_item.user_items.build( :name => "User Item 1" )
user_item.save
This should yield the results you're looking for.
For more on relationships refer to the associations module on ActiveRecord.
精彩评论