虽然视图包含(我相信)是显示提要的正确UNLESS语句,但当用户没有关注任何人时,来自micropost.rb模型的SQL方法似乎无效。此错误在部署环境(例如Heroku)中是透明的 - 这是从应用程序生成500响应的日志片段:
Started GET "/" for 71.180.163.2 at Mon Jan 31 12:10:07 -0800 2011
Processing by PagesController#home as HTML
Completed in 9ms
ActiveRecord::StatementInvalid (PGError: ERROR: syntax error at or near ")"
LINE 1: ...* FROM "microposts" WHERE (user_id IN () OR user_...
^
: SELECT "microposts".* FROM "microposts" WHERE (user_id IN () OR user_id = 1) ORDER BY microposts.created_at DESC LIMIT 30 OFFSET 0):
app / controllers / pages_controller.rb:6:在'home'
问题是,如何在没有黑客修复的情况下解决此问题,例如在User.create上自动关注用户!
它有帮助,这个问题的要点是:https://gist.github.com/804754
答案 0 :(得分:1)
删除微博模型中的初始self.from_users_followed_by方法,让私有的self.followed_by(用户)方法独立,似乎解决了这个问题。所有测试都通过了。
来自models / micropost.rb
class Micropost < ActiveRecord::Base
attr_accessible :content
belongs_to :user
validates :content, :presence => true, :length => { :maximum => 140 }
validates :user_id, :presence => true
default_scope :order => 'microposts.created_at DESC'
#Return microposts from the users being followed by the given user--
scope :from_users_followed_by, lambda { |user| followed_by(user) }
#
# def self.from_users_followed_by(user)
# followed_ids = user.following.map(&:id).join(", ")
# where("user_id IN (#{followed_ids}) OR user_id = ?", user)
# end
private
#Return an SQL condition for users followed by the given user.
#We include the user's own ID as well--
def self.followed_by(user)
followed_ids = %(SELECT followed_id FROM relationships
WHERE follower_id = :user_id)
where("user_id IN (#{followed_ids}) OR user_id = :user_id",
:user_id => user)
end
end
答案 1 :(得分:1)
无需像在from_users_followed_by
方法中那样手动构建查询字符串。我会做类似的事情:
def self.from_users_followed_by(user)
followed_ids = user.following.map(&:id) + user.id
where(:user_id => followed_ids)
end