Rails:如何在setter方法中使父属性可用 [英] Rails: How to make available parent attribute in setter method
问题描述
上下文:
我有一个company
模型,其中有许多projects
和许多tasks
. company
也有很多employees
,而它们又有很多tasks
.
I have a company
model with many projects
, having many tasks
. The company
also has many employees
, which in turn have many tasks
.
架构:
问题:
我正在构建一个表单来创建一个项目,用户可以在其中添加多个tasks
.提交后,表单应创建单个project
记录,一个或多个具有hours
和employee_id
属性的task
记录,并(!)检查数据库中是否已经存在employee
名称或创建一个新的
I'm building a form to create a project where the user can add multiple tasks
. Upon submission the form should create a single project
record, one or more task
records with hours
and employee_id
attributes and (!) check if the employee
name already exists in the database or create a new one.
我已经通过在表单中添加jquery autocomplete
并在Task模型中使用getter
和setter
方法定义了虚拟属性来实现此目的.类似于铁路#102 .
I've approached this by adding jquery autocomplete
to the form and defining a virtual attribute with a getter
and setter
method in my Task model. Similar to Railscast #102.
此操作成功在tasks
中设置了employee_id
,并使用员工name
和task_id
创建了新的employee
记录.
This succesfully sets the employee_id
in tasks
and creates a new employee
record with employee name
and task_id
.
问题是当前模型未保存company_id
.
The problem is currently that the model does not save a company_id
.
我的代码:
class Task < ActiveRecord::Base
belongs_to :project
belongs_to :employee
def employee_name
employee.try(:name)
end
def employee_name=(name)
self.employee = Employee.find_or_create_by(name: name) if name.present?
end
end
问题:
如何使父模型的company_id
属性可用于我的Task
模型的setter方法?像这样:
How can I make the company_id
attribute of the parent model available the setter method of my Task
model? Like so:
def shareholder_name=(name)
self.shareholder = Shareholder.find_or_create_by(name: name, company_id: company_id) if name.present?
end
此刻会产生错误:
undefined local variable or method "company_id" for #<Task:0x98438b8>
或者,如果我尝试project.company_id
,这告诉我project
是NilClass:
Or, if I try project.company_id
this tells me project
is a NilClass:
undefined method company_id for nil:NilClass
更新:
仍未解决.为什么在这里project
是nil
的任何想法?
Still unsolved. Any ideas why project
is nil
here?
推荐答案
class Task < ActiveRecord::Base
belongs_to :project
belongs_to :employee
def shareholder_name=(name)
self.shareholder = Shareholder.find_or_create_by(name: name, company_id: project.company_id) if name.present?
end
end
还有一个典型的带有Rails的模式,例如您拥有belongs_to :project
,它将在Task
中添加一个名为project
的实例方法,然后该实例方法可用于获取与任务关联的项目,并随后使用如果可能感兴趣的话,关联的company_id
also, so typical pattern with rails, for instance where you have belongs_to :project
, that would add an instance method called project
to Task
, that instance method could then be used to get project associated with task and subsequently the associated company_id
in case that may be of interest
这篇关于Rails:如何在setter方法中使父属性可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!