我有一个简单的应用程序,有三个模型,分类,项目和分类:
class Category < ActiveRecord::Base
has_many :categorizations, :dependent => :destroy
has_many :projects, :through => :categorizations
end
class Project < ActiveRecord::Base
has_many :categorizations, :dependent => :destroy
has_many :categories, :through => :categorizations
accepts_nested_attributes_for :categorizations
end
class Categorization < ActiveRecord::Base
belongs_to :project
belongs_to :category
end
我想使用单个表单来创建新项目并将类别与其关联。传递Categorization模型数据的表单部分如下所示:
<div class="field">
<strong>Categories:</strong><br>
<%= f.fields_for :categorizations do |category| %>
<%= collection_check_boxes :categorization, :category_ids, @categories, :id, :display_name %>
<% end %>
</div>
......控制器的相关部分如下所示:
def create
@project = Project.new(project_params)
@categorizations = @project.categorizations.build(categorization_params)
respond_to do |format|
if @project.save && @categorizations.save
format.html { redirect_to @project, notice: 'Project was successfully created.' }
format.json { render action: 'show', status: :created, location: @project }
else
format.html { render action: 'new' }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
def categorization_params
params.require(:project).permit(:project_ids => [], :category_ids => [])
end
当我尝试使用此表单创建新记录时,它成功创建了一个新的Project记录,但Categorization记录未通过category_ids。当我查看日志时,它似乎将category_ids作为字符串数组传递:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"zt3KGmB20OA28P7Y21QvYjTkJvJg+gQnjOcp//XNB2I=", "project"=>{"slug"=>"new-project-31", "title"=>"New Project 31", "body"=>"Design & research", "published"=>"false"}, "categorization"=>{"category_ids"=>["1", "2", ""]}, "commit"=>"Create Project"}
INSERT INTO "categorizations" ("created_at", "project_id", "updated_at") VALUES (?, ?, ?) [["created_at", Mon, 03 Mar 2014 00:36:09 UTC +00:00], ["project_id", 27], ["updated_at", Mon, 03 Mar 2014 00:36:09 UTC +00:00]]
任何有关如何从表单创建个别分类记录的帮助都将非常感谢!
答案 0 :(得分:0)
我不确定这是否有效,因为您没有显示错误消息。但我猜这是因为你没有向构建方法提交正确的参数。
尝试将数组映射到类似
的哈希... build(categorization_params.map {| cat | cat})
修改强>
讨论后:
@project.categorizations.build(params[:categorization][:category_id].map{|cat| {category_id: cat}}