views:

769

answers:

2

Hello, I'm trying to insert a drop down menu values to a table named units and that drop values are coming from another model named properties.

Here is the schema of the units.

create_table "units", :force => true do |t|
    t.string   "number"
    t.decimal  "monthly_rent"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "property_id"
  end

on my view/units/new.html.erb I have this.

<% form_for @unit do |f| %>
<%= f.error_messages %>
<p>
    <%= f.label :property_id %>
    <br/>
    <%= select (:unit, :property_id, Property.all.collect  {|property| [property.name,property.id,]}) %>
</p>
<p>
    <%= f.label :number %>
    <br/>
    <%= f.text_field :number %>
</p>
<p>
    <%= f.label :monthly_rent %>
    <br/>
    <%= f.text_field :monthly_rent %>
</p>
<p>
    <%= f.submit "Submit" %>
</p>
<% end %>

And here is my controller method

def create
    @unit = Unit.new(params[:unit])
 # @unit.property_id = 1

    if @unit.save
      flash[:notice] = "Successfully created unit."
      redirect_to @unit
    else
      render :action => 'new'
    end
  end

Only number and monthy_rent getting inserted to the table but the property_id doesn't come. Can some body help me on this please? Thanks

A: 

The possible issue I can see from what you've shown us is the errant comma in your select helper. Try rewriting it like this (also using the form helper method):

<%= f.select :property_id, Property.all.collect {|property| [ property.name, property.id ] } %>

And yes, the output of the create params to your log would help immensely.

Ben
Surprisingly the superfluous comma doesn't cause any problems. Calling select as a method of the form might make a difference, but given, the form declaration, I don't expect it to.
EmFi
Good point, trailing commas are totally acceptable in ruby arrays. I don't think that `property` is a reserved/danger word in ruby or rails... got nothing with this code.
Ben
I had a nearly identical response until I realized that. Decided it would make more sense to wait for the params that chase ghosts.
EmFi
Hi Ben, thank you for the reply. I tried that but still I get a nil for the property_id (rdb:7) @unit.inspect "#<Unit id: 36, number: \"1001\", monthly_rent: #<BigDecimal:7f067f46de80,'0.15E4',9(18)>, created_at: \"2009-11-26 11:25:06\", updated_at: \"2009-11-26 11:25:06\", property_id: nil>" (rdb:7)
randika
A: 

I figured it out, sorry guys it was my mistake. It was not working because, property_id is not added to the attr_accessible, once I added that it worked. but I still don't know the exact issue yet.

class Unit < ActiveRecord::Base
  belongs_to :property
  attr_accessible :number, :monthly_rent, :property_id
end
randika