Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 3 在Rails find/where中传递多态查找参数的对象_Ruby On Rails 3_Where Clause_Belongs To_Polymorphism - Fatal编程技术网

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