我一整天都在拼命工作,無法完成這項工作。我對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在研究員表中)。所以我自己就完成了這個查詢。
所有的數據似乎都在那裏,但作爲'原始屬性'。
任何幫助將不勝感激!
- 詹姆斯
當你在ActiveRecord中進行多個連接時,它會有一些愚蠢的訪問數據。這可能是因爲你需要通過'@student [「name」]'而不是通常的方式訪問它。 – octopushugs
謝謝@octopushugs,我認爲你是沿着正確的路線,但是沒有工作:( –