我有一个模型 Project
,它有许多 ProjectGenres
引用 Genres
:
class Project < ActiveRecord::Base
has_many :project_genres
accepts_nested_attributes_for :project_genres, allow_destroy: true
has_many :genres, through: :project_genres
end
class ProjectGenre < ActiveRecord::Base
belongs_to :project
belongs_to :genre
end
class Genre < ActiveRecord::Base
has_many :project_genres
has_many :projects, through: :project_genres
end
当我创建一个项目时,我想勾选它所属的适当流派。然后,当他们提交此表单时,它应该在 ProjectGenre
表中创建相应的记录。
我的表单中有以下行:
<%= f.collection_check_boxes(:project_genres, Genre.all, :id, :description) %>
虽然我不太确定我在 Controller 中做了什么?我在 params[:project][:project_genres]
中传回了一个数组(尽管它传回了一个额外的空条目),但我是否应该在这里自己创建嵌入式对象,还是我错过了一些能够自动创建这些的东西?
最佳答案
我不是 Rails 专家,但也许我可以提供帮助。
尝试将助手更改为如下所示。
<%= f.collection_check_boxes(:genres_ids, Genre.all, :id, :description) %>
然后在 Controller 中
def create
@project = Project.new(project_params)
respond_to do |format|
if @project.save
format.html { redirect_to @project , notice: 'Project was successfully created.' }
else
format.html { render action: 'new' }
end
end
end
如果您使用的是 Rails 4 或 strong_params gem,则必须允许 genres_ids
#I will asume Project model has a name attribute
def project_params
params.require(:project).permit(:name, :genres_ids => [])
end
我认为您在使用 collection_check_boxes
助手时不需要使用 accepts_nested_attributes_for
。
关于mysql - 使用 collection_check_boxes 有困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20658759/