【问题标题】:How to save to two models at once using Rails and has_many through association?如何通过关联使用 Rails 和 has_many 一次保存到两个模型?
【发布时间】:2013-12-21 14:28:01
【问题描述】:

在我的 rails 3.2 站点中,我有用户和社区。当用户创建新社区时,我希望用户也自动成为该社区的成员。会员制形成了另一种模式。关系如下:

用户:

has_many :memberships
has_many :communities, :through => :memberships

社区:

has_many :memberships
has_many :users, :through => :memberships

会员:

belongs_to :user
belongs_to :community

那么简而言之,我如何在使用 user_id 和 member_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

结束

【问题讨论】:

    标签: ruby-on-rails-3 has-many-through


    【解决方案1】:

    如果用户创建这样的社区,这应该可以工作:

    user.communities.create
    

    From the Rails guide:

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

    physician.patients = patients

    会为新关联的对象创建新的连接模型,如果其中一些已经消失,它们的行将被删除。

    【讨论】:

    • 谢谢。你能解释一下这在控制器中的样子吗?
    • 当然.. 将您的控制器添加到您的问题中。
    • 你可以通过current_user访问用户吗(如果你添加了该方法进行身份验证)?如果是这样:@community = current_user.communities.build(params[:community])
    • 您需要某种方式来找到创建社区的用户。
    • 是的,我有 current_user。并且代码不会产生错误,但也不会产生关联;只是新社区。我需要保存新社区和协会。
    【解决方案2】:

    有效的答案是这样的:

    def create
      @community = current_user.communities.create(params[:community])
    
      respond_to do |format|
        if @community ...
    

    问题在于使用 build 和 @community.save。这并没有挽救协会。使用 .create 会自动调用 new 并保存并创建关联。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-24
      • 2016-12-23
      • 1970-01-01
      • 2013-11-24
      • 1970-01-01
      相关资源
      最近更新 更多