在我的rails 3.2站点中,我有用户和社区。当用户创建新的社区时,我希望用户也自动成为该社区的成员。会员资格形成另一种模式。的关系如下:如何通过关联使用Rails和has_many一次保存到两个模型?
用户:
has_many :memberships
has_many :communities, :through => :memberships
社区:
has_many :memberships
has_many :users, :through => :memberships
成员:
belongs_to :user
belongs_to :community
一言以蔽之的话,我怎么在创建一个成员同时我使用user_id和membership_id显然创建了一个社区?
更新
控制器动作:
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
末
谢谢。你能解释一下这在控制器中的样子吗? – Finnjon
当然..添加你的控制器到你的问题。 – benjaminjosephw
我已经完成了。在评论中看起来不太好。 – Finnjon