使用collection_check_boxes时遇到困难

我有一个模型Project ,其中有许多引用Genres ProjectGenres

 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表中创建适当的记录。

我的表格中有以下内容:

  

我不确定我在控制器中做了什么? 我在params[:project][:project_genres]传回了一个数组(虽然它传回了一个额外的空条目),但是我应该在这里自己创建嵌入对象的驴工作,或者我错过了什么能够自动创建这些吗?

我不是铁路专家,但也许我可以提供帮助。

尝试将帮助器更改为这样。

 <%= f.collection_check_boxes(:genres_ids, Genre.all, :id, :description) %> 

然后在控制器中

 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

如果你使用form_for,你真的需要发布更多的表单代码…

 <%= form_for @project do |f| %> ... <% end %> <%= f.fields_for :genres do |builder| %> <%= render "genre_fields", :f => builder %> <% end %> 

因为这可以解决问题。 可能会发布更多您的表单代码