【问题标题】:Rails Dropdown has_many throughRails Dropdown has_many 通过
【发布时间】:2016-05-19 22:59:29
【问题描述】:

我无法将 id 保存在连接表 (document_configuration) 中。

我有树模型:

文档.rb

belongs_to :languages
has_many :document_configurations
has_many :document_catalogs, through: :document_configurations

accepts_nested_attributes_for :document_catalogs
accepts_nested_attributes_for :document_configurations

document_catalog.rb

has_many :document_configurations
has_many :documents, through: :document_configurations

document_configuration.rb

belongs_to :document
belongs_to :document_catalog

所以,我想在我的document_form 中获取所有document_catalog 的列表所以,当我创建一个新文档时,我可以包含相应的目录。

这是我的表格:

<div class="form-group">
  <%= f.select :document_catalog_ids, DocumentCatalog.all.collect {|x| [x.name, x.id]}, {}%>
</div>

正在列出我想要的目录。

这是我的控制器:

def new
 @document = Document.new
 @document.document_catalogs.build
end

def document_params
  params.require(:document).permit(:name, :description, :document_file,
  :language_id, {:document_catalog_ids=>[]}) #I tried this too: :document_catalog_ids=>[] without the {}
end

我刚刚收到此错误:Unpermitted parameter: document_catalog_ids 我真的需要在document_configuration 模型中保存 document_iddocument_catalog_id

另一件事是:我需要在我的创建、更新和销毁方法中添加任何其他内容吗?

【问题讨论】:

  • 找出问题所在的最佳方法是检查传入控制器的实际参数。您可以这样做,例如将puts params.inspect 作为def document_params 的第一行,然后运行该操作并检查服务器窗口中的输出。通常这会让你看到你缺少什么(例如嵌套级别)。
  • 您的连接表违反了常规。 Rails 期望连接表的名称始终按词法顺序排列,因此请尝试将表名称更改为“configuration_documents”,看看是否可以解决问题。在此处查看文档并查看第 3.3.2 节 guides.rubyonrails.org/…
  • 谢谢你们。我检查显示参数,然后更改模型名称。这种方式我还是有问题,所以我稍微改了一下逻辑

标签: ruby-on-rails nested-forms nested-attributes has-many-through model-associations


【解决方案1】:

未经许可的密钥的处理

默认情况下,未明确允许的参数键将记录在开发和测试环境中。在其他环境中,这些参数将被过滤掉并忽略。

此外,可以通过更改环境文件中的config.action_controller.action_on_unpermitted_parameters 属性来更改此行为。如果设置为:log,则会记录未经许可的属性,如果设置为:raise,则会引发异常。

在 GitHub 的文档中找到这个:https://github.com/rails/strong_parameters#handling-of-unpermitted-keys

【讨论】:

  • 谢谢@astelvidaxror 我正在尝试不同的方法。但是,感谢您的评论,我学到了一些新东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-19
  • 2013-11-18
  • 2017-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多