2017-04-20 128 views
0

我一整天都在拼命工作,無法完成這項工作。我對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,我認爲你是沿着正確的路線,但是沒有工作:( –

回答

1

而不是試圖加入東西放進一個回報(如您在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