Getting a strange nil in Rails with Select
I'm getting a strange nil problem with the following code.
The view (part of it):
<p>
<%= label :maintenance, :name %>
<%= text_field(:maintenance, :name, :size => 20) %>
</p>
<p>
<%= label :maintenance, :type %>
<%= select :maintenance, :type, @m_types %>
</p>
If I remove the text_field or move it below the select, I get a nil for the :maintenance in the select.
the controller method:
def new
@log = Log.new
@maintenance = Maintenance.new
@m_types = Maintenance.types
@cars = Car.all
print @maintenance
if not params[:car].nil?
@log.car = params[:car]
end
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @log }
end
end
I'm assuming it must be some strange Ruby evaluation thing, but I have no idea what I'm 开发者_运维问答looking for. I searched around with Google, but not knowing what you're searching for makes that pretty hard.
TIA!
Thanks to all who helped out, but I refactored my models, changed my inheritance column and it works now. I think the problem was that I was using :type as the inheritance column, so when I asked to set the :type in the select before I did the text_field it didn't know I was using a Maintenance object and it was looking for a regular object. Any normal Ruby object uses the :type field for something else. So it was looking for the :type set to a module, and not to a String as I was trying to do.
You can see my new setup that's working. Hope someone can learn from this.
I highly suggest that you use the form_for method to declare your forms.
In your case you can do (in your view):
form_for @maintenance do |f|
f.label :name
f.text_field :name
end
This will attach the form variables to your instance of @maintenance.
Check out this guide for more info on forms in Rails - Dealing with Model Objects in Forms
精彩评论