Ruby on rails 3 在Rails find/where中传递多态查找参数的对象
假设我有:Ruby on rails 3 在Rails find/where中传递多态查找参数的对象,ruby-on-rails-3,where-clause,belongs-to,polymorphism,Ruby On Rails 3,Where Clause,Belongs To,Polymorphism,假设我有: class Comment < ActiveRecord::Base belongs_to :commentable, :polymorphic => true end class Article < ActiveRecord::Base has_many :comments, :as => :commentable end class Photo < ActiveRecord::Base has_many :comments, :as =
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
class Article < ActiveRecord::Base
has_many :comments, :as => :commentable
end
class Photo < ActiveRecord::Base
has_many :comments, :as => :commentable
#...
end
这在rails(rails 3)中似乎不起作用。生成的查询似乎没有将多态对象扩展为可注释的\u id和可注释的\u类型字段:
SQLite3::SQLException: no such column: comments.commentable:
我是ruby和rails的新手,所以我可能错误地使用了这个范例,但我的期望是rails能够自动扩展
:commentable => @jims_photo
致:
Rails指南是最好的指南之一,因此我建议您开始阅读 您的类声明看起来不错,我假设您也是迁移。但只是为了它。假设它看起来像这样:
class CreateComment < ActiveRecord::Migration
def change
create_table :comments do |t|
t.string :name
t.references :commentable, :polymorphic => true
# this is the equivalent of
# t.integer :commentable_id
# t.string :commentable_type
t.timestamps
end
end
end
如果您想真正安全地使用:
:commentable_id => @jims_photo.id, :commentable_type => @jims_photo.class.name
然后我建议将.class.name
替换为.base\u class
(您实际上不需要名称
:to\u s
返回name
,并将自动调用)
这样做的原因是,当ActiveRecord为多态关联保存\u类型
时,它将使用base\u类
,以确保它不会保存本身是多态类的类
如果你玩store\u full\u sti\u class
,你可能需要采取更多的预防措施
我强烈建议查看Rails的STI代码。@jims\u photo.comments不起作用?什么是基本类?我得到了NoMethodError:undefined方法'base_class'@fatuhoku。
class CreateComment < ActiveRecord::Migration
def change
create_table :comments do |t|
t.string :name
t.references :commentable, :polymorphic => true
# this is the equivalent of
# t.integer :commentable_id
# t.string :commentable_type
t.timestamps
end
end
end
def self.find_by_parent(parent)
where(:commentable_id => parent.id, :commentable_type => parent.class.name)
end
:commentable_id => @jims_photo.id, :commentable_type => @jims_photo.class.name