2012-10-29 31 views
1

我有以下型號:確保陣列中的至少一個項目存在於另一個

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 

任何想法我做錯了什麼?

+0

我不明白..只顯示帖子,至少有1個國家? – Lichtamberg

回答

2

問題是,您正嘗試使用之前未定義的實例變量@user_country_posts,因此其值爲nil

在生產線:

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

你實際上是在呼籲@user_country_posts變量,這相當於因此與上nil調用++方法。

嘗試初始化變量的方法開始,如:

@user_country_posts = [] 
+0

這工作得很好。謝謝。 –

0

我也考慮使用Ruby的工會的做法: 即:

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

所以,如果你有一個清單用戶國家和發佈國家名單,然後可能下面的工作: 即:

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

從上面的更新看來,您希望顯示的所有帖子都包含用戶的國家代碼之一。如果是這樣的話,我會做以下: 即:

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

上述應工作假設你正確配置的關係。

+0

不幸的是,這不起作用,因爲Post和Countries之間的關係是通過由於HABTM關係而生成的連接表(countries_posts)完成的。此外,您的最後一條命令是否顯示所有*國家與用戶國家匹配的帖子? –

相關問題