使用 collection_check_boxes 的困难 [英] Difficulty using collection_check_boxes

查看:24
本文介绍了使用 collection_check_boxes 的困难的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型 Project,它有许多引用 GenresProjectGenres:

I have a model Project which has many ProjectGenres which references 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 表中创建相应的记录.

When I create a project, I want to tick the appropriate genres it affiliates with. Then when they submit this form, it should create the appropriate records in the ProjectGenre table.

我的表单中有以下行:

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

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

I'm not really sure what I do in the controller though? I get an array passed back in params[:project][:project_genres] (although it passes back an extra empty entry), but am I supposed to do the donkey work here in creating the embedded objects myself, or am I missing something to be able to just create these automatically?

推荐答案

我不是 Rails 专家,但也许我可以提供帮助.

I'm not a rails expert but maybe i can help.

尝试将助手更改为如下所示.

Try changing the helper to look like this.

<%= 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,则必须允许流派_ids

And you have to permit genres_ids if you are using Rails 4 or the strong_params gem

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

I think you don't need to use the accepts_nested_attributes_for when you are are using the collection_check_boxes helper.

这篇关于使用 collection_check_boxes 的困难的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆