Rails / Mongoid“String类型的值不能写入Array类型的字段”

时间:2014-09-16 21:56:24

标签: ruby-on-rails mongoid

我正在使用Rails 4.1和Mongoid 4.0,而且我对这两者都很陌生。

我正在尝试在Ingredients类和Recipe类之间进行简单的N-N引用关系。

我有这个:

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>

我认为这种关系设置正确,但我不理解错误。

1 个答案:

答案 0 :(得分:2)

你的问题是:

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

将所选项目作为字符串发送到服务器:

<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>

在这种情况下params[:post][:author_id] == '1',您需要[1]

要确保使用以下方式发送数组:

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

这允许选择多个项目并发送一组ID [1,2,3]

Docs