views:

69

answers:

2

Hello. I have a very simple problem but cannot find a nice solution. I have a lookup code in ruby (for example, Students that live in a State):

# State lookup (id, name)
class State < ActiveRecord::Base
    has_many :students
end

# Class that belogs to a state
class Student< ActiveRecord::Base
    belongs_to :state
end

and in the view/students/new.html.erb view, I display the states as a drop down:

  <p>
    <%= f.label :state %><br />
    <%= f.collection_select :state, State.find(:all), 
       :id, :name, :prompt => "Select a State" %>
  </p>

so far, so good, but when I hit save I got an error:

State(#37872860) expected, got String(#21001240)

what seems reasonable, as I'm sending a string instead of a State object to the Student.create method.

Which is the best way of handling this in RoR? I'm getting the State object in the controller by hand and replacing it in the parameters hash, but I think should be a better way.

Thanks very much. Fernando

A: 
<%= f.collection_select :state_id, State.find(:all), :id, :name, :prompt => "Select a State" %>

:state_id not :state

jdl
Thanks JDL, but tried that and now I'm getting: undefined method 'state_id' for #<State:xxxxxxxx> on the render stage.
Fernando
Can you post the form_tag line from your view?
jdl
jdl, thanks very much. The problem was that in my students table, the state column was named 'state', not 'state_id'. This made :state_id fall if referenced in the view. Thanks to your hint found the problem in the table, re-create it and now it is working as you said (f.collection_select :state_id, ... same as it was).Regards;fernando
Fernando
A: 

State.find(:all) should really be something that happens in your controller not your view. I don't even think its possible to access a model in the view, which may be your problem. If you do something like this in your controller:

@states = State.find(:all)

Then you use the @states variable in the view:

<%= f.collection_select :state_id, :name, :prompt => "Select a State" %>

I hope that helps.

Mike Williamson