【问题标题】:using nested forms with has_many through - can't assign mass attributes通过 has_many 使用嵌套表单 - 无法分配质量属性
【发布时间】:2013-01-31 22:03:25
【问题描述】:

我已经阅读了几乎所有关于通过关联使用 has_many 嵌套表单的问题,但我无法让我的模型工作。有人可以帮忙吗?

有 2 种模型:原型和裙子偏好,通过裙子偏好模型链接。

以下是模型:

class Archetype

has_many :skirtpreferences has_many :SkirtPreferences, :through => :skirtpreferences 接受_nested_attributes_for :SkirtPreferences 接受_nested_attributes_for :skirtpreferences 结束

块引用

类 Skirtpreferencing

belongs_to :archetype belongs_to :SkirtPreferences
Accept_nested_attributes_for :SkirtPreferences

结束

类 SkirtPreference

has_many :skirtpreferences has_many :archetypes, :through => :裙子偏好

结束

表单看起来像这样,显示得很好:

... builder %> ...

我想我必须在控制器中做一些事情,但我不确定具体是什么。

谢谢!

添加控制器:

class ArchetypesController < ApplicationController

 def new
 @archetype = Archetype.new
 @archetype.skirtpreferencings.build
end

    # GET /archetypes/1/edit
def edit
  @archetype = Archetype.find(params[:id])
end

 def create
 @archetype = Archetype.new(params[:archetype])     
end 


class SkirtPreferencesController < ApplicationController   

 def new
 @skirt_preference = SkirtPreference.new
 end 

 def edit
 @skirt_preference = SkirtPreference.find(params[:id])
 end


 def create
 @skirt_preference = SkirtPreference.new(params[:skirt_preference])

 end

【问题讨论】:

  • 是否为 ArchetypesController 中的new 方法生成了表单?
  • 请将您的代码删减到问题部分。

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


【解决方案1】:

我猜这是 SkirtPreference 和 Archetype 之间的多对多关系,而 SkirtPreferencing 是 SkirtPreference 和 Archetype 之间的关联?

尝试将skirtpreferencing_attributes 更改为skirtpreferences_attributes。这是我的预感。因为您正在尝试将数据添加到 skritpreferences,而不是仅用于关联裙子偏好和原型的裙子偏好。

我也觉得这很不寻常。

has_many :SkirtPreference, :through =&gt; :skirtpreferencings

accepts_nested_attributes_for :SkirtPreference

...

belongs_to :SkirtPreference

accepts_nested_attributes_for :SkirtPreference

所有这些通常应该是:skirtpreferences


** 编辑 1 **

假设表单是在 ArchetypesController 中的新操作中生成的...

您似乎错过了根据原型构建裙子偏好属性的部分。

所以在 ArchetypesController 中的新操作中

def new
  @archetype = Archetype.new
  @archetype.skirtpreferencings.build
  ...
end

** 编辑 2 **

SkirtPreferences 应改为skirtpreferences,类名除外。

您可以尝试将f.fields_for :skirtpreferencing do 更改为f.fields_for :skirtpreferencings do

【讨论】:

  • 您好,感谢您的快速回复。进行了您建议的更改-相同的消息。但是对于您的第一个问题:是的,通过裙子偏好,SkirtPreference 和 Archetype 之间的多对多。
  • 可以复制粘贴错误信息吗?我想找出导致错误的属性。
  • 无法批量分配受保护的属性:裙子偏好
  • 尝试将&lt;%= f.fields_for :skirtpreferencing do |preference_builder| %&gt; 更改为&lt;%= f.fields_for :skirtpreferencings do |preference_builder| %&gt;。与s
  • 我意识到当我尝试做其他事情时发生了什么。当我为 SkirtPreference 生成脚手架时,我使用了skirt_preference 而不是 SkirtPreference。在这个过程中,我似乎把自己和红宝石弄糊涂了。我将恢复到以前的版本并重新开始这些模型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-04
  • 1970-01-01
  • 1970-01-01
  • 2013-04-18
相关资源
最近更新 更多