has_many:through 为连接模型传递额外的属性值
这是我的模型定义
class Partner < ActiveRecord::Base
has_many :projectcollaborations
has_many :projects, :through => :projectcollaborations, :source => :project
end
class Project < ActiveRecord::Base
has_many :projectcollaborations
has_many :partners, :through => :projectcollaborations, :source => :partner
end
class Projectcollaboration < ActiveRecord::Base
belongs_to :project
belongs_to :partner
end
我的连接表看起来像下面的
+--------------+--------------+------+-----+-------------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+-------------+-------+
| project_id | int(11) | NO | PRI | 0 | |
| partner_id | int(11) | NO | PRI | 0 | |
| project_role | varchar(255) | YES | | participant | |
+--------------+--------------+------+-----+-------------+-------+
现在在创建一个新项目时我想在project_role列中传递值“creator”。我怎样才能做到这一点?
当前的创建方法如下所示
def create
@partner = Partner.find(params[:partner_id])
@project = Project.new(params[:project])
@project.partners << @partner
respond_to do |format|
if @project.save
format.html { redirect_to partner_project_path(@partner, @project), notice: 'Project was successfully created!' }
format.json { render json: @project, status: :created, location: @project }
else
format.html { render action: "new" }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
Here is my model definition
class Partner < ActiveRecord::Base
has_many :projectcollaborations
has_many :projects, :through => :projectcollaborations, :source => :project
end
class Project < ActiveRecord::Base
has_many :projectcollaborations
has_many :partners, :through => :projectcollaborations, :source => :partner
end
class Projectcollaboration < ActiveRecord::Base
belongs_to :project
belongs_to :partner
end
My Joined Table Looks like the bellow one
+--------------+--------------+------+-----+-------------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+-------------+-------+
| project_id | int(11) | NO | PRI | 0 | |
| partner_id | int(11) | NO | PRI | 0 | |
| project_role | varchar(255) | YES | | participant | |
+--------------+--------------+------+-----+-------------+-------+
Now while creating a new project i want to pass the value "creator" in the project_role column. How can i achieve this ?
Current create method Looks like the bellow one
def create
@partner = Partner.find(params[:partner_id])
@project = Project.new(params[:project])
@project.partners << @partner
respond_to do |format|
if @project.save
format.html { redirect_to partner_project_path(@partner, @project), notice: 'Project was successfully created!' }
format.json { render json: @project, status: :created, location: @project }
else
format.html { render action: "new" }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论