记录不会插入到has_many的联接表中:通过关联

时间:2014-11-06 16:20:44

标签: ruby-on-rails activerecord

我有2个模型:UserCollective,以及他们的联接表Membership。当用户创建新的集合时,我想同时在两者之间创建新的成员资格。现在我的创建功能部分工作,因为集体的新功能是表单向我的数据库添加了一个集体记录,但没有添加成员资格记录。

用户模型

class User < ActiveRecord::Base
    has_many :collectives, :through => :memberships
    has_many :memberships
end

集体模式

class Collective < ActiveRecord::Base
    has_many :users, :through => :memberships
    has_many :memberships
end

会员资格模式

class Membership < ActiveRecord::Base
    belongs_to :user
    belongs_to :collective

    validates :user_id, presence: true
    validates :collective_id, presence: true
end

集体管理员

def new
    @collective = Collective.new if user_signed_in?
end

def create
    @collective = Collective.new(collective_params)

    if @collective.save
        current_user.memberships.create(collective_id: @collective) 
        flash[:success] = "Collective created!"
        redirect_to collective_url(@collective)
    else
        render 'new'
    end
end

private

    def collective_params
        params.require(:collective).permit(:name, :description, :location, :num_of_users, :num_of_projects)
    end

end

日志

Started POST "/collectives" for 127.0.0.1 at 2014-11-06 10:49:39 -0500
Processing by CollectivesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"Dh/rG1N6ulrJSIiEaAgudnaltjxnKwCw5sdUQxG9qnE=", "collective"=>{"name"=>"Honda Civic", "location"=>"Cars", "description"=>"Blaahhhhh"}, "commit"=>"Create Collective"}
  User Load (0.2ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 1  ORDER BY "users"."id" ASC LIMIT 1
   (0.1ms)  begin transaction
  SQL (0.6ms)  INSERT INTO "collectives" ("created_at", "description", "location", "name", "num_of_projects", "num_of_users", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?)  [["created_at", "2014-11-06 15:49:40.003338"], ["description", "Blaahhhhh"], ["location", "Cars"], ["name", "Honda Civic"], ["num_of_projects", 0], ["num_of_users", 1], ["updated_at", "2014-11-06 15:49:40.003338"]]
   (145.3ms)  commit transaction
   (0.0ms)  begin transaction
   (0.1ms)  commit transaction
Redirected to http://localhost:3000/collectives/7
Completed 302 Found in 208ms (ActiveRecord: 146.7ms)

由于某种原因似乎忽略了行current_user.memberships.create(collective_id: @collective),因为重定向很正常。非常感谢帮助。提前致谢!

1 个答案:

答案 0 :(得分:0)

我会说问题是传递实例对象而不是id。它应该是:

if @collective.save
    current_user.memberships.create(collective_id: @collective.id) 
    flash[:success] = "Collective created!"
    redirect_to collective_url(@collective)
else
    render 'new'
end

由于create方法仅返回true/false(由于验证而在此情况下为false)并且不会引发任何异常,因此会将其重定向到show操作。