mysql - 使用 collection_check_boxes 有困难

标签 mysql ruby-on-rails ruby-on-rails-4

我有一个模型 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/

相关文章:

mysql - MySQL其他列如何与其他列聚合

MYSQL 初学者 ORDER By - 只需要列中每个条目的最大值

mysql - 动态生成的字段不保存

html - 对于大多数静态页面和少量表单的网站,Rails 是否是一个足够轻便的解决方案?

ruby-on-rails - 如何通过 Assets 管道加载css.erb文件

ruby-on-rails - 加载常量时自动加载常量时检测到循环依赖

mysql - 如何使用mysql计算时间总和

ruby-on-rails - 以 rails 形式存储和检索 postgres 嵌套的 JSONB 数据类型

ruby-on-rails-4 - 捆绑安装在 ubuntu 15.04 上给我 rmagick 错误

php - 在数据库中的同一个表中使用连接