user2040981
user2040981

Reputation: 1

Rails/Mongoid "Value of type String cannot be written to a field of type Array"

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.

Upvotes: 0

Views: 1582

Answers (1)

sites
sites

Reputation: 21795

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.

Upvotes: 2

Related Questions