Betjamin Richards
Betjamin Richards

Reputation: 941

Ensuring at least one item in an array exists in another

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?

Upvotes: 1

Views: 525

Answers (2)

Patelify
Patelify

Reputation: 1800

I would also consider using ruby's union approach: ie:

[1,2,4] & [1,4,5]
=> [1,4]

So if you have list of user countries and a list of post countries then maybe the below would work: ie:

@shared_country_ids = @user.countries.map(&:id) & @post.countries(&:id)

From your update above what it seems like you want to do is show all posts that have one of the user's country codes. If that's the case I would do the below: ie:

@posts = Post.where(:countries => @user.countries)

The above should work assuming you configured the relationships correctly.

Upvotes: 0

KARASZI Istv&#225;n
KARASZI Istv&#225;n

Reputation: 31467

The problem is that you're trying to use the @user_country_posts instance variable which was not defined before, so its value is nil.

At the line:

@user_country_posts += Country.find(user_country.id).posts

You're actually calling the + method on the @user_country_posts variable, which is equivalent therefore with calling + on a nil.

Try to initialize the variable in the beginning of the method, like:

@user_country_posts = []

Upvotes: 2

Related Questions