سؤال

I have these models:

class Users < ActiveRecord::Base      
  has_many  :members
  has_many  :organizations, :through => :members
end

class Organizations < ActiveRecord::Base 
  has_many  :members
  has_many  :users, :through => :members 
end

class Members < ActiveRecord::Base 
 belongs_to :organizations
 belongs_to :users
end

I would like to create a Member record as follows:

  1. A user logs in
  2. Navigates to a specific organization's 'show' page
  3. Clicks on a link labeled 'Join'

I've read through several posts on the site asking similar questions; however, most are when one of the records is being created at the same time. Here is what I've tried:

In my organization's controller I created a join method:

# PATCH/PUT /organizations/1/join
def join
  @membership = @organization.members.new(user_id: current_user.id)
  if @membership.save
    flash[:success] = "Your have successfully joined #{@organization.name}!"
    redirect_to @organization
  else
    flash[:error] = "There was an error."
    render 'show'
  end
end

In my routes file, I added a join link:

resources :organizations do
  member do
    post :join
  end
end

On my organization's show page, I added a link as follows:

<% if @organization.members.where("user_id = ?", @current_user).exists? %>
  # Unjoin link
<% else %>
  <%= link_to 'Join!', join_organization_path,
                       :method => "post" %>
<% end %>

Here is my server log error:

Started POST "/organizations/2/join"
Processing by OrganizationsController#join as HTML
Parameters: {"authenticity_token"=>"...=", "id"=>"2"}
Completed 500 Internal Server Error in 1ms

NoMethodError (undefined method `members' for nil:NilClass):
app/controllers/organizations_controller.rb:47:in `join'

Thanks for your help.

هل كانت مفيدة؟

المحلول

Set the instance variable @organization in join method.

def join
  @organization = Organization.find(params[:id]) ## Set @organization
  @membership = @organization.members.new(user_id: current_user.id)
  if @membership.save
    flash[:success] = "Your have successfully joined #{@organization.name}!"
    redirect_to @organization
  else
    flash[:error] = "There was an error."
    render 'show'
  end
end

You are getting NoMethodError (undefined method 'members' for nil:NilClass) error because @organization instance variable is nil (not set) and you are calling members method on nil object.

If you have a before_action callback setup in your controller to set @organization variable then you can just add join as an option in it.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top