活动记录表加入

问题描述:

我一整天都在拼命工作,无法完成这项工作。我对Ruby和Rails很陌生,所以我对任何愚蠢的错误表示歉意。活动记录表加入

我的问题是我加入3个表一起得到一个@students对象。这有效,但如果我打电话给例如@ student.name那么'名称'不存在。

下面是我的代码:

控制器 注意到我一直在使用.includes和。加入和相同的问题发生尝试。

class MyprojectController < ApplicationController 
    def show 
    @project = Project.find(params[:id]) 
    @dateformat = '%b %e - %H:%M' 
    @user = Student.includes("INNER JOIN researchers ON students.researcher_id = researchers.id 
           INNER JOIN users ON researchers.user_id = users.id").where('user_id = ?', current_user.id) 

end 

用户模型

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 

研究员模型

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

学生模型

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 

所以每个学生都有一个researcher_id,每个研究员都有一个user_id。所以连接应该是student-> researcher-> user,然后我希望能够使用@user对象中所有表中的所有属性。

我尝试使用Student.join(:研究员,:用户),但试图做从学生表到研究员表的联接,然后尝试通过使用学生表中的user_id加入用户表(但的user_id在研究员表中)。所以我自己就完成了这个查询。

所有的数据似乎都在那里,但作为'原始属性'。

任何帮助将不胜感激!

- 詹姆斯

+0

当你在ActiveRecord中进行多个连接时,它会有一些愚蠢的访问数据。这可能是因为你需要通过'@student [“name”]'而不是通常的方式访问它。 – octopushugs

+0

谢谢@octopushugs,我认为你是沿着正确的路线,但是没有工作:( –

而不是试图加入东西放进一个回报(如您在SQL)使用includes这样您就可以访问较少的查询所有的数据,但你仍然可以访问你的数据对象。使用像ActiveRecord这样的ORM的要点是能够使用对象访问数据。使用ORM的不利之处在于,有时它不能有效地获取所需的确切数据,因为数据正在推入对象。使用includes提供了一种中间立场,您可以在对象中访问所需的数据,并且不必为每个关联运行查询。

试着这么做(取决于你如何让你的用户名 - 我从项目的假设):

@user = User.includes(researcher: :student).find(project.user_id)

然后你就可以通过正常的轨道协会访问的事情:

researcher = @user.researcher

student = researcher.student

我希望帮助和祝你好运!

+0

只是试过这个,它仍然不工作不幸。首先它能够找到researchcher = @ user.researcher研究员,但然后无法找到student = researcher.student的学生;其次,即使没有创建研究员和学生对象,我仍然无法访问用户部分的属性。感谢您的帮助,尽管 –

+0

另一个可能的解决方案是执行'joins'就像你现在正在做的那样,但是在你需要的字段上运行一个手动的'select'并且重新绑定它们,比如'select(“users.name as user_name”)',那么你应该能够找到你想要的东西 – octopushugs

+0

这里的根本问题是,rails关联没有按预期方式加载吗?也许你的sql模式设置不正确?你能加载一个用户对象并访问它的关联fr在轨道控制台? (运行'bin/rails console'进入控制台)。从rails控制台中,您应该能够构建各种模型和关联,以便按照您的预期测试一切正在保存到数据库。 – Puhlze