2013-12-21 62 views
0

在我的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 

回答

0

工作的答案是这样的:

def create 
    @community = current_user.communities.create(params[:community]) 

    respond_to do |format| 
    if @community ... 

的问题是使用生成并@ community.save。这并没有挽救协会。使用.create会自动调用new并保存并创建关联。

1

如果用户创建了这样一个社区这应该工作:

user.communities.create 

From the Rails guide:

可以通过API管理连接模型的集合。例如,如果您分配

physician.patients = patients

新加入模型为新关联的对象创建的,如果一些都消失了,他们的记录被删除。

+0

谢谢。你能解释一下这在控制器中的样子吗? – Finnjon

+0

当然..添加你的控制器到你的问题。 – benjaminjosephw

+0

我已经完成了。在评论中看起来不太好。 – Finnjon

相关问题