我有以下型号:
class Project < ActiveRecord::Base
has_many :memberships
has_many :users, through: :memberships
end
class User < ActiveRecord::Base
has_many :memberships
has_many :projects, through: :memberships
end
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :project
end
以及会员资格的迁移
def change
create_table :memberships do |t|
t.belongs_to :user
t.belongs_to :project
t.boolean :admin
end
end
在我的控制器中,我想为当前用户创建一个项目
def create
@project = current_user.projects.build(project_params)
if @project.save
render json: @project, status: :ok
else
render json: { errors: @project.errors }, status: :unprocessable_entity
end
end
def project_params
params.require(:project).permit(:name)
end
调用@project.save
时,日志中的SQL:
INSERT INTO "projects" ("created_at", "name", "updated_at") VALUES (?, ?, ?) [["created_at", "2014-12-09 17:18:55.298566"], ["name", "Test"], ["updated_at", "2014-12-09 17:18:55.298566"]]
因此,会员资格永远不会更新,因此项目会被制作,但它与当前用户无关。我认为rails应该在使用关系构建对象时自动执行,但这似乎不是这种情况。
如果我这样做,它将起作用
@project = current_user.projects.build(project_params)
@project.users << current_user
但这感觉不对。我哪里错了?