0

I have two models, Ingredients and Foods:

class Food < ActiveRecord::Base

    belongs_to :user
    has_many :ingredients

    accepts_nested_attributes_for :ingredients

    attr_accessible :name, :price
end

class Ingredient < ActiveRecord::Base

    belongs_to :user
    belongs_to :food

    attr_accessible :ingredient_name, :quantity_used
end

The schemas for the two models are as follows:

  create_table "foods", :force => true do |t|
    t.string  "name"
    t.integer "user_id"
    t.float   "price"
    t.string  "ingredient_name"
  end

  create_table "ingredients", :force => true do |t|
    t.string  "ingredient_name"
    t.integer "user_id"
    t.integer "food_id"
    t.integer "quantity_used"
  end

I'm creating a form for Food which also creates/updates the Ingredient table as well. I have the form working, and the submit button updates the correct attributes, but I have other attributes in each table that I want to update as well. For example, in the Food Controller, I want to do something like ingredient.user_id = current_user.id. I understand I can access things through params[:food], but how do I access individual fields which aren't being updates by the form?

Right now, my form is:

<%= form_for(@food) do |f| %>
  <div class="field">
    <%= f.label :Name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :price %><br />
    <%= f.number_field :price %>
  </div>
    <div>
        <%= f.fields_for :ingredients do |builder| %>
        <%= builder.label "Ingredient Used:" %>
        <%= builder.text_field :ingredient_name %><br />
            <%= builder.label "Quantity Used:" %>
            <%= builder.text_field :quantity_used %><br />
        <% end %>
    </div>
    <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

How do I access this specific Food's ingredients in the Food#create action?

Thanks!

2
  • Similar to your earlier question - stackoverflow.com/questions/16073617/…. Also, have a look at the documentation Commented Apr 28, 2013 at 23:47
  • The answer there didn't work for me originally. Looking back, I had a typo, and now it works. Thanks. Commented Apr 29, 2013 at 2:19

1 Answer 1

2

You might need to add :ingredients_attributes to attr_accessible in your Food model.

You can mess about with the params hash in the controller by iterating over the :ingredients_attributes or you can use assign_attributes.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.