【问题标题】:model from ActiveRecord query has no attributes来自 ActiveRecord 查询的模型没有属性
【发布时间】:2017-04-22 18:07:02
【问题描述】:

我在了解 ActiveRecord 和创建关联方面遇到了一些实际问题,所以我确信我的错误很简单。

我有一个 @user 对象,我称之为:

@user = User.joins(researchers: :students).select(user_attributes).find(current_user.id)

user_attributes = 'researchers.year, users.givenname,... 等等。

这很好用。当我尝试运行非常相似的行时:

@supervisor = User.joins(researchers: :supervisors).select(supervisor_attributes).where('supervisor.student_id = ?', 1)

supervisor_attributes = 'user.surname'在哪里

当我尝试调用 @supervisor.surname 时,我得到一个无方法错误,我完全不知道为什么。

我尝试了一些数字或解决方法,但我认为我的代码和关联存在更根本的错误,如下所示:

student.rb

class Student < ApplicationRecord
  #Must have the following
  validates :name, :email, :surname, :email, :supervisor, :registration_number, presence: true
  #ensures unique email addresses
  validates :email, uniqueness: true

  #assosiations
  belongs_to :researcher
end

supervisor.rb

class Supervisor < ApplicationRecord
  belongs_to :researcher
end

researcher.rb

class Researcher < ApplicationRecord
  #belongs_to :project
  belongs_to :user
  has_many :supervisors
  has_many :students
end

user.rb

class User < ApplicationRecord
  include EpiCas::DeviseHelper

  has_many :event_registrations
  has_many :events, through: :event_registrations
  belongs_to :project
  has_many :researchers
  has_many :students, :through => :researchers
  has_many :supervisors, :through => :researchers

  # def self.authenticate(username)
  #   where(username: username).first
  # end

  end

任何帮助将不胜感激!

非常感谢, 詹姆斯

【问题讨论】:

  • 能否发布错误信息

标签: sql ruby-on-rails ruby activerecord multiple-inheritance


【解决方案1】:

不应该是复数吗?

supervisor_attributes = 'users.surname'

【讨论】:

  • 你是对的,应该是这样,但不幸的是,同样的错误发生了,谢谢!
  • 在哪里,supervisors
  • 你可以像@supervisor = User.joins(researchers: :supervisors).select(supervisor_attributes).where(supervisors: { student_id: 1 })一样重写它
  • 等等,我明白了。你有一个 ActiveRecord::Relation,而不是一个主管,这就是问题所在。因为在哪里。它始终是一个结果集,即使只有一个元素。
  • 在第一个示例中,您使用的是find,而不是where
【解决方案2】:

你能试试下面的查询吗

supervisor_attributes = 'users.surname'

@supervisor = User.joins(researchers: :supervisors).select(supervisor_attributes).where('supervisors.student_id = ?', 1)

where clause 中,您应该使用database table name,按照惯例,它应该是复数supervisors

【讨论】:

  • 嗨,Rokibul,我刚刚尝试过,这与我得到的错误相同。不过谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-22
  • 2011-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多