[英]Rails 4: can't update polymorphic object
My object Item
has polymorphic association as element
(It can be a video, texte etc.) 我的对象Item
具有多态关联作为element
(它可以是视频,文本等)
When I want to update the Item
(and his element
) I do this : 当我想更新Item
(及其element
)时,我这样做:
@item.update_attributes(param_update_item)
I call this : 我这叫:
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
the permitted params is good, but when the update_attributes
is called, I get an error : 允许的params是好的,但是当调用update_attributes
时,我收到一个错误:
undefined method `primary_key' for ActionController::Parameters:Class
Any idea? 任何想法?
EDIT : 编辑:
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
and an exemple of model (in my example) 和模型的例子(在我的例子中)
class Texte < ActiveRecord::Base
include Element
validates :content, :presence => true
end
My Item in DB : 我在DB中的项目:
class Item < ActiveRecord::Base {
:id => :integer,
:element_id => :integer,
:element_type => :string,
.... }
and when I do item.element
I get : 当我做item.element
我得到:
=> <Texte id: 15757, content: "RE3 3232 /...", created_at: ...>
If you want to update your element with your item, you should tell the model that your item should accept nested attributes for element. 如果要使用项目更新元素,则应告诉模型您的项目应接受元素的嵌套属性。
module Element
included do
has_one :item, :as => :element, dependent: :destroy
accepts_nested_attributes_for :element
end
end
But I think you might have your relationships set up incorrectly. 但我认为您的关系设置可能不正确。 You say that you want your element to be polymorphic, but your item only belongs to element. 你说你希望你的元素是多态的,但你的项目只属于元素。
I would do 我会做
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
Then in your item update, you can permit 然后在您的项目更新中,您可以允许
element_attributes: [# all your element attributes in here]
This would require you to change the item table to have element_id and add elements table in a migration 这将要求您将项表更改为具有element_id并在迁移中添加元素表
create_table :elements do |t|
t.belongs_to :elementable, polymorphic: true
end
This would create columns named elementable_type and elementable_id 这将创建名为elementable_type和elementable_id的列
I would read this for more info Polymorphic Associations 我想读更多信息多态关联
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.