从对象创建关联

时间:2015-06-21 22:22:11

标签: ruby-on-rails activerecord

class Group < ActiveRecord::Base
  has_many :memberships
  has_many :users, through: :memberships
end

class Membership < ActiveRecord::Base
  belongs_to :user
  belongs_to :group
end

以下在成员资格表中成功创建了一个新关联:

def create
  @group = Group.find(params[:group_id])
  current_user.groups << @group
  flash[:success] = "You have successfuly joined this group."
  respond_to do |format|
    format.html {redirect_to @group}
    format.js
  end
end

但是我想测试首先创建的关联,并显示适当的flash消息,例如:

def create
  @group = Group.find(params[:group_id])
  membership = current_user.memberships.create(@group)
  if membership.save
    flash[:success] = "You have successfuly joined this group."
  else
    flash[:error] = "Unable to join this group."
  end  
  respond_to do |format|
    format.html {redirect_to @group}
    format.js
  end
end

此代码错误:

"ArgumentError (When assigning attributes, you must pass a hash as an argument.):"

是否可以使用现有对象创建关联?

1 个答案:

答案 0 :(得分:0)

membership = current_user.memberships.create({group_id: @group.id})