开发者

CRUD for table with foreign key

I have table A with foreign key to table B in field b_id. Now I'm trying to make view/control for adding new table A entry. In form I have combo box (via collectio开发者_运维知识库n_select) that lists all the elements from table B and that is where i intend to get the b_id for new instance of A in the create method for A.

Value of the combo box is set to the id of the desired B instance. But how do I set that value to the new A object's b_id field in th ecreate method? What ever I try, it is always NULL and of course, I get the exception.


I'm not sure I follow your question exactly, but it sounds like you may want to pass the ID directly from the params to the new A object's create method... something like this:

a = A.create( :b_id => params[:b_id], ... )

It all really depends on what you've named the combo box in your view. If you could paste a snippet of your view then that would help


Update based on comment.

Looking at the rails docs for collection_select, it looks like you're not passing the right data to collection_select


First things first, have you declared that B has many As, and that A belongs to B in your models? (edit: had these reversed originally)

class B < ActiveRecord::Base
  has_many :as
end

class A < ActiveRecord::Base
  belongs_to :b
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜