Note that there are some explanatory texts on larger screens.

plurals
  1. POMy has_many :through association of Users, Groups, and Memberships is causing trouble in some methods
    text
    copied!<p>I am working with a has_many :through association: Users join Groups through a Membership. I am having trouble with some methods I created in the user model to determine if the user is a member of a group, and to allow a user to join and leave a group. Using the console, <code>memberships.find_by_group_id</code> always returns nil. I am not sure why and I think it might be the way I have set up my has_many :through associations, though after looking it over many, many times and consulting railscasts/blogs it seems ok. If you want me to post more info, like the schema.db or something, let me know</p> <pre><code>class User &lt; ActiveRecord::Base has_many :memberships, :dependent =&gt; :destroy has_many :groups, :through =&gt; :memberships . . . def member?(group) memberships.find_by_group_id(group) end def join!(group) memberships.create!(:group_id =&gt; group.id) end def leave!(group) memberships.find_by_group_id(group).destroy end . . . end class Group &lt; ActiveRecord::Base has_many :memberships has_many :members, :through =&gt; :memberships, :source =&gt; :user has_attached_file :photo, :styles =&gt; { :thumb =&gt; "100x100", :small =&gt; "200x200" } attr_accessible :name, :description, :private, :created_at, :group_id attr_accessible :photo, :photo_file_name, :photo_content_type, :photo_file_size, :photo_updated_at end class Membership &lt; ActiveRecord::Base attr_accessible :group_id belongs_to :user belongs_to :group end </code></pre> <p>Here is the membership controller:</p> <pre><code>class MembershipsController &lt; ApplicationController def create @group = Group.find(params[:membership][:group_id]) current_user.join!(@group) respond_to do |format| format.html { redirect_to @group } format.js end end def destroy @group = Membership.find(params[:id]).group current_user.leave!(@group) respond_to do |format| format.html { redirect_to @group } format.js end end def index @memberships = Membership.all end end </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload