2010-08-19 54 views
0

我有3個模型(用戶 - 會員 - 社區)如何從集合選擇中的活動記錄中檢索信息?

用戶可以成爲許多社區的成員。爲此,我創建了一個包含user_id,community_id的成員資格。

連接後,用戶必須選擇一個社區。模型用戶作爲包含該獨特社區的community_id。

編輯時,他將能夠改變這個社區。

如果我這樣做:

<%= f.collection_select :community_id, Community.find(:all), :id, :name, { :allow_blank => 'Select a community' }, :style => "width: 200px;" %> 

所有社區快樂,也是他不是成員誰。 我嘗試這樣做:

<%= f.collection_select :community_id, Membership.find(:all), :community_id, :id, { :allow_blank => 'Select a community' }, :style => "width: 200px;" %> 

但我只顯示號碼:成員的(ID)... 我怎樣才能加入這個ID與社區的名字嗎?

回答

1

我認爲你接近你的第一次嘗試,而不是找到你需要的所有社區,只需找到該用戶是其成員的社區。因此,而不是Community.find(:all)你可以使用:

Community.find(:all, 
       :includes => :memberships, 
       :conditions => ['memberships.user_id = ?', @user.id]) 

這是假設你有一個@user變量設置爲您的觀點。您需要這樣才能將查找限制爲您的用戶所屬的社區。

它還假定有一個關聯Communityhas_many :memberships。我猜你已經從這個問題中得到了答案。

2

不知道這是否會工作,但嘗試一下:

member.rb # add a method to the member model that returns the 
def community_name 
    community.name 
end 

#view 
<%= f.collection_select :community_id, Membership.find(:all, :include => :community), :community_id, :community_name, { :allow_blank => 'Select a community' } %> 

的:包括選項預取的成員集合中的所有社區在一個查詢。