2015-12-06 30 views
1

所以,我有這個線在我的控制器:任何方式來避免這可能是不必要的查詢?

if Account.includes(:student).where(:email => account[:email]).any? 
     student=Account.find_by_email(account[:email]).student 
     @stream.students << student 
     else 
     #... 
     end 

在這裏,我想這提出了兩個的數據庫查詢,而不是一個,爲條件,和裏面,如果爲真。

回答

2

我從記憶和打字怎麼回事iPad,但我認爲你可以這樣做:

if student = Student.joins(:account).find_by(accounts: { email: account[:email] }) 
    ... 
end 
0

更改爲:

student = Account.includes(:student).where(:email => account[:email]).first 
if student 
# code 

first返回的第一條記錄或無這要是零失敗的if語句。

+0

這難道不是建立學生爲帳戶的實例? –

+0

是的,上面的答案是正確的,我最初讀錯了問題。 – CWitty

0

我認爲下面的代碼將使它:

student_account = Account.includes(:student).where(:email => account[:email]).first 
if !student_account.nil? 
    student=student_account.student 
    @stream.students << student 
else 
    #... 
end 
0

我想,我想看看作爲重組:

if student = Student.joins(:accounts). 
        where(:accounts => {:email => account[:email]}). 
        take 
    @stream.students << student 
    else 
    #... 
    end 

我在這裏做一些猜測你的模型和協會,當然,但這是返回Student的單個查詢。

+0

這個問題,downvoter? –

+0

這個返回的是一個關係而不是一個學生對象,如上所述 –

+0

看上去很好 - 我需要一個調整。 –

相關問題