Ruby on rails ActiveRecords未调用正确的SQL语句
我在ActiveRecords上遇到了一个奇怪的问题,我已经挣扎了几天了。我还是rails的初学者,希望stackoverflow上的rails大师能告诉我我做错了什么 我使用的是postgres服务器,在资源和评论之间有一种多对一的关系。 我在我的控制器上有一个操作,我通过ajax调用该操作来检索特定资源的所有注释。 我使用这个方法,它应该返回属于特定资源id的所有注释Ruby on rails ActiveRecords未调用正确的SQL语句,ruby-on-rails,postgresql,activerecord,Ruby On Rails,Postgresql,Activerecord,我在ActiveRecords上遇到了一个奇怪的问题,我已经挣扎了几天了。我还是rails的初学者,希望stackoverflow上的rails大师能告诉我我做错了什么 我使用的是postgres服务器,在资源和评论之间有一种多对一的关系。 我在我的控制器上有一个操作,我通过ajax调用该操作来检索特定资源的所有注释。 我使用这个方法,它应该返回属于特定资源id的所有注释 def forresource resource_id = params[:id] @comments = Resource
def forresource
resource_id = params[:id]
@comments = Resource.find_by_id(resource_id).comments
respond_to do |format|
format.html
format.json { render :status=>200, :json=>{:success=>true, :comments => @comments}}
end
end
但是,在运行时,此方法似乎是在搜索带有注释id的注释
Started POST "/comments/30/forresource" for 127.0.0.1 at 2013-03-04 19:49:05 -0700
Processing by CommentsController#forresource as JSON
Parameters: {"id"=>"30"}
Comment Load (0.4ms) SELECT "comments".* FROM "comments" WHERE "comments"."id" = $1 LIMIT 1 [["id", "30"]]
Completed 404 Not Found in 10ms
ActiveRecord::RecordNotFound - Couldn't find Comment with id=30:
谁能告诉我我做错了什么?
我也试过这个命令
@comments = Comment.where(:resource_id => resource_id)
以下是简化的模型关系
class Resource < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
attr_accessible :content, :resource_id, :user_id
belongs_to :user
belongs_to :resource
end
我试过:
class Resource < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
attr_accessible :content, :resource_id, :user_id
belongs_to :user
belongs_to :resource
end
您提到使用CanCan,您是使用load_和授权资源还是load_资源?如果是这样,您将需要从该控制器中排除这些操作,以便CanCan不会尝试从您的资源路由加载注释。或者,您可以更改您的路由,以便资源在其“内部”具有按路由的注释
后一种方法是最干净、资源丰富的路由,在您的场景中通常会有/resources/:resource\u id/注释。您是否使用InheritedResources或任何类似的方法来尝试自动加载注释?我怀疑你的代码甚至没有被访问,你可以通过查看错误的堆栈跟踪来确认这一点。您是否正在使用cancan?是的,我们正在使用cancan 1.6.7。cancan怎么能使这复杂化呢?我们正在使用cancan,这也是这个错误开始出现的时间。这是一个已知的问题吗?对吗?我不明白为什么它对我们不起作用!就好像铁轨神在攻击我们你是通灵者吗?!就是这样。谢谢
class Resource < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
attr_accessible :content, :resource_id, :user_id
belongs_to :user
belongs_to :resource
end
1.9.3-p392 :026 > Comment.where(:resource_id => resource_id).to_sql
=> "SELECT `comments`.* FROM `comments` WHERE `comments`.`resource_id` = 5"
1.9.3-p392 :028 > Resource.where(id: 1).first.comments.to_sql
Resource Load (1.9ms) SELECT `resources`.* FROM `resources` WHERE `resources`.`id` = 1 LIMIT 1
=> "SELECT `comments`.* FROM `comments` WHERE `comments`.`resource_id` = 1"