Rails: How to make available parent attribute in setter method

邮差的信 提交于 2019-12-05 22:05:16
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 

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!