2016-08-30 194 views
0

我學習Ruby on Rails,我想加入兩個模型(表)。 User.rb(用戶表)ActiveRecord :: StatementInvalid在Hr#internal_employee_page

class User < ActiveRecord::Base has_many :offer_letters end 

OfferLetter.rb(offer_letter表)

class OfferLetter < ActiveRecord::Base belongs_to :user end 

HrController(hr_controller.rb)

class HrController < ApplicationController 
    def internal_employee_page 
     @employees = OfferLetter.joins(:user).where(:id => :candidate_id)  
end 

運行時,我的代碼我得到錯誤「Mysql2 ::錯誤:'on子句'中的未知列'offer_letters.user_id':SELECT offer_letters。* FROM offer_letters INNER JOIN users ON usersid = offer_lettersuser_id其中offer_lettersid = NULL」

<div id="job_details"> 
    <% @employees.each do |emp| %> 
     <%= render partial: "hr/employee_details", locals: {emp: emp} %> 
    <% end %>    
</div> 

錯誤在這行:<%@ employees.each做| EMP |%> 那麼告訴我,我錯了

+0

當我們使用連接時,我們必須用它的屬性指定表名(應該是複數形式)。所以在你的where子句中,請指定id與其各自的表,如前所示:OfferLetter.joins(:user).where(users.id =>:candidate_id) – Navin

回答

0

當我們使用加入,我們必須指定表。名稱(應爲複數)及其屬性,所以在您的where子句,請與各自的表指定ID像前:

@employees = OfferLetter.joins(:user).where('users.id = ?', candidate_id) 

OR

@employees = OfferLetter.joins(:user).where('offer_letters.id = ?', candidate_id) 
+0

您好納文,我試過這個@employees = OfferLetter.joins(:user ).where('users.id =?',candidate_id)。但是我得到了錯誤「OfferLetter上找不到名爲'user'的錯誤是*****關聯;也許你拼錯了它?*****在同一個地方 –

+0

此錯誤發生後,我也嘗試將關聯規則放入OfferLetter模型belongs_to:用戶和用戶模型has_one:offer_letter然後我得到了以下錯誤:'on子句'中的Mysql2 ::錯誤:未知列'offer_letters.user_id':SELECT'offer_letters'。* FROM'offer_letters' INNER JOIN'users 'ON' users'.'''''offer_letters'.'user_id' WHERE(users.id = 14)「 –

+0

這裏我是」users.id = offer_letters.user_id「而不是」users.id = offer_letthers.candidate_id「因爲users.id等於offer_letters.candidate_id –

相關問題