【问题标题】:Why association does not add a new record to my table?为什么关联不会向我的表中添加新记录?
【发布时间】:2017-03-06 12:02:13
【问题描述】:

我有 2 个模型:Chocolate 和 Kind,其中巧克力类看起来像:

class Chocolate < ActiveRecord::Base
  has_many :kinds, inverse_of: :chocolate
  accepts_nested_attributes_for :kinds

和 Kind 类看起来像:

class Kind < ActiveRecord::Base
  belongs_to :chocolate

我有下一个简单的表格,其中包含:

= simple_form_for @chocolate do |ch|
  = ch.simple_fields_for :kinds, @chocolate.kinds.build(kind: 'Bitter') do |k|
    = k.input :kind
  = ch.input :netto 
  = ch.submit

因此,当我提交表单时,它会向我的chocolates 表添加一条新记录,但它不会通过关联向我的kinds 表添加一条记录。

ChocolateController 我有:

private
def chocolate_params
  params.require(:chocolate).permit(:netto, kinds_attributes: [:kind])
end

那么,为什么它不通过关联写入我的表?我哪里错了?

【问题讨论】:

  • 能否添加参数日志?
  • Parameters: {"utf8"=&gt;"✓", "authenticity_token"=&gt;"iu7...YPw==", "kind"=&gt;{"kind"=&gt;"Bitter"}, "chocolate"=&gt;{"netto"=&gt;"500 gr"}, "commit"=&gt;"Create Chocolate"}@prakashS 请
  • 您允许kinds_attributes 其中kind 在实际参数中。这意味着您不会获得新种类的属性。
  • 您的问题是您的嵌套模型没有正确嵌套在表单中。您需要将simple_fields_for :kinds 更改为ch.simple_fields_for :kinds。我以前没有使用过 simple_form,但这是使用标准 Rails 表单助手的方式。

标签: ruby-on-rails model-view-controller associations nested-attributes


【解决方案1】:

如何使用简单形式的嵌套模型:https://github.com/plataformatec/simple_form/wiki/Nested-Models

所以,你需要这样的东西:

= simple_form_for @chocolate do |ch|
  = ch.simple_fields_for :kinds ...

【讨论】:

  • 谢谢!那很有用!我解决了这个问题,但没有再发生 =/
猜你喜欢
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 2015-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多