我有两个模型,Recipe
和Tag
,有has_and_belongs_to_many
关系。对于这种关系,我有一个简单的连接表,RecipesTags
.
食谱:
has_and_belongs_to_many :tags
标签:
has_and_belongs_to_many :recipes
现在,在创建新食谱后,用户可以以复选框的形式填写食谱所属的类别,例如“肉”、“鱼”等。这些类别实际上只是数据库中的标签。
问题:食谱没有保存任何标签。
配方new
和create
控制器方法:
def new
@recipe = Recipe.new
@ingredients = Ingredient.all
@tags = Tag.all
respond_to do |format|
format.html # new.html.erb
format.json { render json: @recipe }
end
end
# POST /recipes
# POST /recipes.json
def create
@recipe = Recipe.new(params[:recipe])
if (params[:tags])
@recipe.tags << params[:tags]
end
respond_to do |format|
if @recipe.save
format.html { redirect_to @recipe, notice: 'Recipe was successfully created.' }
format.json { render json: @recipe, status: :created, location: @recipe }
else
format.html { render action: "new" }
format.json { render json: @recipe.errors, status: :unprocessable_entity }
end
end
end
风景:
<%= form_for(@recipe, :html => {:multipart => true}) do |f| %>
<% if @recipe.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@recipe.errors.count, "error") %> prohibited this recipe from being saved:</h2>
# [ fields that get's saved for the recipe and works fine ]
<% @tags.each do |t| %>
<%= f.label t.name %>
<%= f.check_box :tags, t.name %>
<br />
<% end %>
<%= f.submit 'Submit recipe', :class => 'btn btn-primary' %>
<% end %>
目前,我收到一条错误消息:“Meat”的未定义方法“合并”:字符串
“肉”是标签名称。
那么,我在这里做错了什么?