我有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和社区的名字联系起来?
发布于 2010-08-20 06:41:19
我认为你的第一次尝试更接近了,但你只需要找到用户所属的社区,而不是找到所有的社区。因此,您可以使用以下命令来代替Community.find(:all):
Community.find(:all,
:includes => :memberships,
:conditions => ['memberships.user_id = ?', @user.id])这里假设您已经为视图设置了@user变量。您需要这样做才能将查找限制到您的用户所属的社区。
它还假设在Community上有一个关联:has_many :memberships。我猜你已经从问题中得到了答案。
发布于 2010-08-20 06:38:48
不确定这是否会起作用,但尝试一下:
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' } %>:include选项在一个查询中预取成员资格集合中的所有社区。
https://stackoverflow.com/questions/3526508
复制相似问题