使用Rails设置Feed

时间:2010-10-25 18:58:16

标签: ruby-on-rails

我有一个国家/地区模型和地点模型 - 国家has_many个地方,以及一个地方belongs_to一个国家/地区。地方模型也has_many个帖子(belong_to个地方)。我想将属于某个国家/地区的所有帖子汇总到Feed中 - 而不是像社交网站上的朋友活动Feed。我在找出适当的搜索方面遇到了一些麻烦,任何帮助都会非常感激!目前我有:

country.rb

has_many :places
has_many :posts, :through => :places

def country_feed
  Post.from_places_belonging_to(self)
end

post.rb

belongs_to :place
scope :from_places_belonging_to, lambda { |country| belonging_to(country) }

private

  def self.belonging_to(country)
    place_ids = %(SELECT place_id FROM places WHERE country_id = :country_id)
    where("place_id IN (#{place_ids})", { :country_id => country })
  end

end

然后在国家show.html.erb文件中:

<h3>Posts</h3>

<% @country.country_feed.each do |post| %>
  <%= link_to "#{post.user.username}", profile_path(post.user_id) %> posted on <%=link_to "#{post.place.name}", place_path(post.place_id) %> <%= time_ago_in_words post.created_at %> ago:
  <%= simple_format post.content %>
<% end %>

这样运行没有任何错误,但提供了所有帖子的提要,而不是选择该特定国家/地区的帖子。让这个工作的最佳方法是什么?我有一种潜在的怀疑,可能会让事情过于复杂......提前谢谢!

1 个答案:

答案 0 :(得分:2)

看起来子查询中存在语法错误。 places_id表中不存在places,因此它应该读取:

SELECT id FROM places WHERE country_id = :country_id

您认为无效子查询会引发异常,但它不会引发异常 - 否则会以静默方式处理。很奇怪。

但除非我遗漏了某些东西,否则只需使用以下内容即可替换所有这些:

<% @country.posts.each do |post| %>

没有

相关问题