为了扩展this guide以创建与同一个表的多个关联,我提出了以下用户类
class User < ActiveRecord::Base
has_secure_password
validates_uniqueness_of :email
validates_presence_of :email
validates_presence_of :name
belongs_to :role
has_many :clients, foreign_key: 'rep_id'
has_many :submitted_jobs, class_name: 'WorkOrder', through: :clients
has_many :processing_tasks, class_name: 'WorkOrder', foreign_key: 'processor_id'
def has_role?(role_sym)
role.name.underscore.to_sym == role_sym
end
end
我的目标是能够根据用户类型分别引用提交的作业和处理任务。到目前为止,处理任务部分按照我的预期工作,到目前为止,我可以从工作订单中获取代表,但是当我尝试像rep.submitted_jobs这样的时候,我收到以下错误:
NoMethodError: undefined method `to_sym' for nil:NilClass
from /usr/local/rvm/gems/ruby-2.1.5@rails4/gems/activerecord-4.1.6/lib/active_record/reflection.rb:100:in `_reflect_on_association'
ect...
显然,has_many通过关系的工作方式与我期望的不同,但我甚至不确定将这种关系称为什么,所以我对于看起来什么样的东西感到茫然对于。 它可能也值得注意
RSpec.describe User, type: :model do
it {should validate_uniqueness_of(:email)}
it {should validate_presence_of(:name)}
it {should belong_to(:role)}
it {should have_many(:submitted_jobs)}
it {should have_many(:processing_tasks)}
end
全部通过
编辑:
class Client < ActiveRecord::Base
has_many :contacts
has_many :addresses, through: :contacts
has_many :permits
has_many :work_orders
validates :clientnumber, format: { with: /\A\d{3}\z/ },
length: { is: 3 }
belongs_to :rep, class_name: 'User'
belongs_to :default_processor, class_name: 'User'
end
编辑2: 工作单协会
class WorkOrder < ActiveRecord::Base
belongs_to :client
belongs_to :project_type
belongs_to :status
belongs_to :labels
belongs_to :contact
belongs_to :processor, class_name: 'User'
has_one :rep, through: :client, class_name: 'User'
has_one :presort_information
has_one :printing_instructions
has_one :production_details
........
end
答案 0 :(得分:0)
典型的has_many_through_association看起来像
要解决此问题,您可以编写自定义关联,该方法将为您提供相关的work_orders
内部用户模型
def submitted_jobs
WorkOrder.joins(:client).where('clients.rep_id = ?', self.id)
end