我的对象Item
与element
具有多态关联(可以是视频,文本等)。
当我想更新Item
(和他的element
)时,我这样做:
@item.update_attributes(param_update_item)
我称之为:
def param_update_item
params.permit(:name, :visible, :title, element: [:content, :url, :html])
# params.permit(:name, :visible, :title) # - don't get error, but obviously don't ubdate the element
end
允许的参数很好,但是调用
update_attributes
时出现错误: undefined method `primary_key' for ActionController::Parameters:Class
任何想法?
编辑:
class Item < ActiveRecord::Base
belongs_to :element, :polymorphic => true, dependent: :destroy
end
module Element
included do
has_one :item, :as => :element, dependent: :destroy
end
end
和模型的一个例子(在我的例子中)
class Texte < ActiveRecord::Base
include Element
validates :content, :presence => true
end
我在数据库中的项目:
class Item < ActiveRecord::Base {
:id => :integer,
:element_id => :integer,
:element_type => :string,
.... }
当我做
item.element
我得到: => <Texte id: 15757, content: "RE3 3232 /...", created_at: ...>
最佳答案
如果要使用项目更新元素,则应告知模型项目应接受元素的嵌套属性。
module Element
included do
has_one :item, :as => :element, dependent: :destroy
accepts_nested_attributes_for :element
end
end
但是我认为您的人际关系可能设置不正确。您说您希望元素是多态的,但您的项目仅属于element。
我会做
class Item < ActiveRecord::Base
belongs_to :element
end
class Element < ActiveRecord::Base
has_one :item
belongs_to :elementable, polymorphic: true
validates :content, presence: true
end
module Elementable
extend ActiveSupport::Concern
included do
has_one :element, as: :elementable
accepts_nested_attributes_for :element
end
end
class Texte < ActiveRecord::Base
include Elementable
end
然后在您的商品更新中,您可以允许
element_attributes: [# all your element attributes in here]
这将需要您将项目表更改为具有element_id并在迁移中添加elements表
create_table :elements do |t|
t.belongs_to :elementable, polymorphic: true
end
这将创建名为elementable_type和elementable_id的列
我将阅读以获取更多信息Polymorphic Associations
关于ruby-on-rails - Rails 4:无法更新多态对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31790196/