我对 Rails 还很陌生,我得到了这段代码,但我认为我正在阻止它做它的一些 Rails 魔法:
目标:创建一个并让创建者通过表中的方法和关联cause
成为成员。build
has_many :through
Cause_User_Membership
问题:我已经通过创建一个cause
然后“手动”创建一个成员资格来实现它。有没有办法在Cause_User_Membership
创建时自动创建关系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
用户.rb(片段)
has_many :cause_user_memberships
has_many :causes, :through => :cause_user_memberships
原因.rb
attr_accessible :title, :location, :description,...
has_many :cause_user_memberships
has_many :users, :through => :cause_user_memberships
Cause_User_Membership.rb(<--可能不是我最好的模型名称)
# == 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