开发者

Setting up a feed with Rails

开发者 https://www.devze.com 2023-01-21 03:33 出处:网络
I have a country model and a places model - a country has_many places, and a place belongs_to a country. A place model also has_many posts (which belong_to a place). I would like to aggregate all the

I have a country model and a places model - a country has_many places, and a place belongs_to a country. A place model also has_many posts (which belong_to a place). I would like to aggregate all the posts from places that belong to a certain country into a feed - rather like a friend activity feed on a social networking site. I'm having a bit of trouble figuring out the appropriate search to do, any help would be much appreciated! At the moment I have:

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

Then in the country show.html.erb file:

<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 %>

This runs without any errors, but gives a feed of all the posts, rather than开发者_Python百科 selecting the posts for that particular country. What's the best way to get this working? I've got a sneaking suspicion that I might be over-complicating matters...thanks in advance!


It looks like there's a syntax error in the subquery. places_id does not exist in the places table, so it really ought to read:

SELECT id FROM places WHERE country_id = :country_id

You'd think the invalid subquery would raise an exception, but it doesn't -- or else it is handled silently. Very odd.

But unless I'm missing something, you could replace all this just by using:

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

No?

0

精彩评论

暂无评论...
验证码 换一张
取 消