Question

So this is for a school project. We don't have to use Ruby, but I decided to learn a new language along the way. So my question is:

I have an asset that should have foreign keys to the manufacturer, location, and employee tables. It also has many maintenance records.

class Asset < ActiveRecord::Base
  belongs_to :manufacturer
  belongs_to :location
  belongs_to :employee
  has_many :maintenances
end

I'm struggling to understand how I would structure a create method for an asset? I have select boxes working to choose the three values, but I don't know how to associate them correctly to the asset on saving.

Here are the select boxes:

    <p>
        <%= f.label :Manufacturer %>
        <%= select_tag(:Manufacturer, options_from_collection_for_select(Manufacturer.all, :id, :name))%>
    </p>
    <p>
        <%= f.label :Location %>
        <%= select_tag(:Location, options_from_collection_for_select(Location.all, :id, :name))%>
    </p>
    <p>
        <%= f.label :Employee %>
        <%= select_tag(:Employee, options_from_collection_for_select(Employee.all, :id, :email))%>
    </p>

I've struggled creating this for a while now. Thanks.

Was it helpful?

Solution

I think you need to use the foreign_id, not the association name, per the rails docs: "If you are using select (or similar helpers such as collection_select, select_tag) to set a belongs_to association you must pass the name of the foreign key (in the example above city_id)"

Also, this select_tag is unrelated to it's parent form. The select tags name attribute would be wrong. Try: f.select_tag(:employee_id, .....)

Finally, you should try formtastic. I use it when I need to render html forms in rails - it's a good time saver.

OTHER TIPS

You can write the controller action like this (if you follow along with Mario's suggestion too):

def create
  @asset = Asset.create(:employee_id => params[:employee_id], :manufacturer_id ...)
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top