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:
- A user logs in
- Navigates to a specific organization's 'show' page
- 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.