I’m fairly new to Rails, I got this code working but I think I’m preventing it from doing it some of its Rails magic:
Goal: Create a cause and have the creator become a member via the build method and the has_many :through association in the Cause_User_Membership table.
Question: I’ve gotten it to work, by creating a cause and then creating a membership ‘manually.’ Is there a way for the Cause_User_Membership relationship to be created automatically on the creation of a cause?
Cause_Controller.rb
def create
@cause = current_user.causes.build(params[:cause].merge :created_by => current_user.id)
respond_to do |format|
if @cause.save
@membership = current_user.cause_user_memberships.build(:cause_id => @cause.id)
@membership.save
format.json { render :json => {current_user: current_user, results: @cause}}
else
format.json { render :json => {Message: "You messed up"}}
end
end
end
User.rb (snippet)
has_many :cause_user_memberships
has_many :causes, :through => :cause_user_memberships
Cause.rb
attr_accessible :title, :location, :description,...
has_many :cause_user_memberships
has_many :users, :through => :cause_user_memberships
Cause_User_Membership.rb (<–probably not my best model name)
# == Schema Information
#
# Table name: cause_user_memberships
#
# id :integer not null, primary key
# user_id :integer not null
# cause_id :integer not null
# created_at :datetime not null
# updated_at :datetime not null
#
class CauseUserMembership < ActiveRecord::Base
attr_accessible :cause_id, :user_id
belongs_to :user #, :class_name => "User", :foreign_key => "user_id"
belongs_to :cause #, :class_name => "Cause", :foreign_key => "cause_id"
end
Update:
I found a slightly more “magical” way to do this using
accepts_nested_attributes_for. First, add a line to yourCauseUserMembershipmodel:With that change, you can do this:
Because you have told rails to accept nested attributes for the
causeassociation onCauseUserMembership, it will save the new cause you assigned to@membership.causewhen it saves the membership itself. So you can save both the cause and membership records at one time, rather than separately.Original answer:
I think what you’ve done is pretty much the right way to do this. It can be simplified a tad bit: you don’t need to build
causefromcurrent_user, you can just usenew(the:throughassociations oncauseandcurrent_userare set when you create@membership).So like this (I only changed the first line in
create):See also: Many-to-Many through association Build/Create properties in Rails app