开发者

How can I retrieve information from an active record with collection select?

开发者 https://www.devze.com 2023-01-12 13:48 出处:网络
I have 3 models (Users - Membership - Community) The users can become members to many communities. For this I made a Membership that contain the user_id, community_id.

I have 3 models (Users - Membership - Community)

The users can become members to many communities. For this I made a Membership that contain the user_id, community_id.

After connected, the user have to choose a community. The model User as a community_id that contain that unique community.

When editing, he would be able to change this community.

If I do this :

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

All the communities happier, also that who he is not member. I tried this :

<%= f.collection_select :community_id, Membership.find(:all), :community_id, :id, { :allow_blank => 'Select a community' }, :style => "wi开发者_运维问答dth: 200px;" %>

But I show only the number (:id) of the Membership… How can I join this id with the name of the community ?


Not sure if this will work but try it out:

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' } %>

The :include option prefetches all communities in the membership collection in one query.


I think you were closer with your first attempt but instead of finding all communities you need to just find communities that the user is a member of. So instead of Community.find(:all) you would use:

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

This assumes that you have an @user variable set up for your view. You need this to restrict the find to just communities that your user is a member of.

It also assumes that there's an association on Community: has_many :memberships. I've guessed you've got that already from the question.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号