【发布时间】:2013-09-27 17:18:48
【问题描述】:
我有一个 has_many :through 用户和项目之间的关系,通过所有权加入模型。我希望能够在创建用户和新项目之间的关系时设置所有权模型的属性。这是我目前所拥有的:
def create
@project = Project.new(params[:project])
if @project.save
current_user.projects << @project
flash[:success] = "Project created!"
redirect_to @project
else
flash[:error] = "Project not created."
end
end
基本上,在为给定用户创建新项目时,我不知道如何在所有权模型中设置值“owner_type”,因为我没有直接在项目创建控制器中提及所有权加入模型。我该怎么做?
这是我的所有权(加入)模型:
class Ownership < ActiveRecord::Base
attr_accessible :owner_type
belongs_to :project
belongs_to :user
validates :user_id, :presence => true
validates :project_id, :presence => true
validates :owner_type, :presence => true
end
和我的用户模型:
class User < ActiveRecord::Base
attr_accessible :name, :email, :admin, :projects
has_many :ownerships
has_many :projects, :through => :ownerships
accepts_nested_attributes_for :projects
和我的项目模型:
class Project < ActiveRecord::Base
attr_accessible :name, :description
has_many :ownerships
has_many :users, :through => :ownerships
【问题讨论】:
标签: ruby-on-rails has-many-through