0

I am using Rails 4.1 and Mongoid 4.0 and I'm pretty new to both.

I am trying to do a simple N-N referenced relationship between an Ingredients class and a Recipe class.

I have this:

class Recipe
  include Mongoid::Document
  field :name, type: String
  has_and_belongs_to_many :ingredients

end

class Ingredient
  include Mongoid::Document
  field :name, type: String
  field :price, type: BigDecimal
  has_and_belongs_to_many :recipes
end

def create
    @recipe = Recipe.new(recipe_params)

    respond_to do |format|
      if @recipe.save
        format.html { redirect_to @recipe, notice: 'Recipe was successfully created.' }
        format.json { render :show, status: :created, location: @recipe }
      else
        format.html { render :new }
        format.json { render json: @recipe.errors, status: :unprocessable_entity }
      end
   end
end

def recipe_params
      params.require(:recipe).permit(:name, :ingredient_ids)
end

Recipes Form:
<div class="field">
      <%= f.label :ingredients %><br />
      <%= f.collection_select :ingredient_ids, Ingredient.all, :id, :name %>
</div>

I believe that the relationship is set up correctly but I don't understand the error.

1
  • try printing params in controller p params and and paste that output here, also p recipe_params Commented Sep 16, 2014 at 22:44

1 Answer 1

2

Your problem is that:

  <%= f.collection_select :ingredient_ids, Ingredient.all, :id, :name %>

Sends selected item as String to server:

<select name="post[author_id]">
  <option value="">Please select</option>
  <option value="1" selected="selected">D. Heinemeier Hansson</option>
  <option value="2">D. Thomas</option>
  <option value="3">M. Clark</option>
</select>

In this case params[:post][:author_id] == '1', and you want [1].

To make sure you are sending an array use:

<%= f.collection_select :ingredient_ids, Ingredient.all, :id, :name, {}, multiple: true %>

This allows to select several items and will send an array of ids [1,2,3].

Docs.

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.