views:

47

answers:

2

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 collection_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.

A: 

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

Orion Edwards
Yes, that's exactly what I want. Combobox is created like this:<% form_for(@opstina) do |f| %>...<%= collection_select(:okrug, :id, @okrugs, :id, :naziv) %>Opstina has foreign key okrug_id to Okrug. But I can't get the selected okrug_id. I tried stuff like params[:okrug_id], but it is nil
celicni
try `collection_select(:opstina, :okrug_id, @okrugs, :id, :naziv)` or `f.collection_select(:okrug_id, @okrugs, :id, :naziv)`
Orion Edwards
Thanks! It works with f.collection_select(:okrug_id, @okrugs, :id, :naziv)Problem occured because my select tag looked like this<select id="okrug_id" name="okrug[id]">and it should looked like this<select id="opstina_okrug_id" name="opstina[okrug_id]">(wrong id)
celicni
A: 

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
Ben
No, I haven't (now I added it)
celicni
Ok, you shouldn't need anything else, if there is a `params[:b_id]` in your request.
Ben