Reputation: 671
In my rails 3.2 site I have Users and Communities. When a User creates a new Community I want the User to also automatically become a Member of that Community. Memberships form another model. The relationships are as follows:
User:
has_many :memberships
has_many :communities, :through => :memberships
Community:
has_many :memberships
has_many :users, :through => :memberships
Membership:
belongs_to :user
belongs_to :community
In a nutshell then, how do I create a Membership at the same time as I create a Community using the user_id and membership_id obviously?
Update
Controller action:
def create
@community = Community.new(params[:community])
respond_to do |format|
if @community.save
format.html { redirect_to @community, notice: 'Community was successfully created.' }
format.json { render json: @community, status: :created, location: @community }
else
format.html { render action: "new" }
format.json { render json: @community.errors, status: :unprocessable_entity }
end
end
end
Upvotes: 0
Views: 1200
Reputation: 671
The working answer was this:
def create
@community = current_user.communities.create(params[:community])
respond_to do |format|
if @community ...
The problem was using build and then @community.save. This did not save the association. Using .create automatically calls new and save and creates the association.
Upvotes: 0
Reputation: 4417
This should work if a user creates a community like this:
user.communities.create
The collection of join models can be managed via the API. For example, if you assign
physician.patients = patients
new join models are created for newly associated objects, and if some are gone their rows are deleted.
Upvotes: 1