【发布时间】:2012-10-29 18:03:33
【问题描述】:
我有以下型号:
class Post < ActiveRecord::Base
has_and_belongs_to_many :countries
end
class User < ActiveRecord::Base
has_many :entitlements
has_many :countries, :through => :entitlements
end
帖子索引页面上的帖子必须至少有一个与用户所在国家/地区之一相同的国家/地区。
我在我的模型和冗长的控制器代码中尝试了各种范围,但我不知道如何检查应该是一个简单的关系:Post.countries 中的至少一项是否存在于 User.countries 中。
任何帮助都得到了很大的帮助。
更新:
好的,我的控制器中有以下内容:
def index
@user = current_user
@user.countries.each do |user_country|
@user_country_posts += Country.find(user_country.id).posts
end
@posts = @user_country_posts
end
遍历 user.countries 并查找这些国家/地区的每个帖子。但是当我运行它时,我得到:
NoMethodError: undefined method `+' for nil:NilClass
任何想法我做错了什么?
【问题讨论】:
-
我不明白.. 只显示至少有 1 个国家/地区的帖子?
标签: ruby-on-rails ruby-on-rails-3 activerecord associations