I have the following models:
class Post < ActiveRecord::Base
has_and_belongs_to_many :countries
end
class User < ActiveRecord::Base
has_many :entitlements
has_many :countries, :through => :entitlements
end
Posts on the Post index page must have at least one country that is the same as one of the Users’ countries.
I have tried various scopes in my models and lengthy controller code but I can’t figure out how to check what should be a simple relationship: whether at least one item in Post.countries exists in User.countries.
Any help greatly received.
UPDATED:
Ok, so I’ve got the following in my controller:
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
Which is iterating through the user.countries and finding each post for those countries. But when I run it I get:
NoMethodError: undefined method `+' for nil:NilClass
Any ideas what I’m doing wrong?
The problem is that you’re trying to use the
@user_country_postsinstance variable which was not defined before, so its value isnil.At the line:
You’re actually calling the
+method on the@user_country_postsvariable, which is equivalent therefore with calling+on anil.Try to initialize the variable in the beginning of the method, like: