2010-10-07 29 views
0

我有以下表現:不能夠命令由包括在Rails3中

user.clocks.includes(:users, :runs => :user_runs).find_by_id(params[:id]) 

這似乎很好地工作。但是,當我添加一個命令,就像這樣:

user.clocks.includes(:users, :runs => :user_runs).orders("users.names").find_by_id(params[:id]) 

它打破,出現以下錯誤:

ActiveRecord::ConfigurationError: Association named 'user_runs' was not found; perhaps you misspelled it? 
app/controllers/clocks_controller.rb:19:in `show' 
    test/functional/clocks_controller_test.rb:21:in `__bind_1286475263_942556' 

任何想法,爲什麼?

這個模型看起來是這樣的:

class Clock < ActiveRecord::Base 
    has_and_belongs_to_many :users 
    has_many :runs 
end 

class Run < ActiveRecord::Base 
    belongs_to :clock 
    has_many :user_runs 
    has_many :users, :through => :user_runs 
end 

class UserRun < ActiveRecord::Base 
    belongs_to :run 
    belongs_to :user 
end 

與我調查繼續我已經試過這樣:

ubiquitous_user.clocks.includes(:runs => :user_runs).find_by_id(params[:id]) 

而且我發現它的發電查詢沒有得到user_runs在所有。有些事情很奇怪。

我創建了一組測試,試圖找出發生了什麼事情:

context "A graph of users, clocks, runs, etc" do 
    setup do 
     @users = [] 
     10.times do 
     @users << Factory.create(:user) 
     end 
     @clocks = [] 
     10.times do 
     @clocks << Factory.create(:clock, :users => @users) 
     end 
     @clocks.each do |clock| 
     10.times do 
      run = Factory.create :run, :clock => clock 
      @users.each do |user| 
      Factory.create :user_run, :run => run, :user => user 
      end 
     end 
     end 
     @user = @users.first 
     @clock = @clocks.first 
    end 

    should "find a clock" do 
     assert_not_nil @user.clocks.find(@clock.id) 
    end 

    should "find a clock with users" do 
     assert_not_nil @user.clocks.includes(:users).find(@clock.id) 
    end 

    should "find a clock with users and runs" do 
     assert_not_nil @user.clocks.includes(:users, :runs).find(@clock.id) 
    end 

    should "find a clock with users, runs and user_runs" do 
     assert_not_nil @user.clocks.includes(:users, :runs => :user_runs).find(@clock.id) 
    end 

    should "find a clock with users order by users.name" do 
     assert_not_nil @user.clocks.includes(:users).order("users.name").find(@clock.id) 
    end 

    should "find a clock with users and runs order by users.name" do 
     assert_not_nil @user.clocks.includes(:users, :runs).order("users.name").find(@clock.id) 
    end 

    should "find a clock with users, runs and user_runs order by users.name" do 
     assert_not_nil @user.clocks.includes(:users, :runs => :user_runs).order("users.name").find(@clock.id) 
    end 
    end 

每個測試,但最後一道關口。這不是一個錯誤?

回答

0

它不應該是

user.clocks.find_by_id(params[:id], :include => [:users, {:runs => :user_runs}]) 

+0

不能在Rails 3中,據我所知。這是舊的Rails 2風格;但它應該仍然有效,也許它工作。我會試一試。 – Pablo 2010-10-08 04:40:27

+0

有了這種語法,它似乎工作。感謝您的想法! :) – Pablo 2010-10-08 05:09:59

+0

實際上,它在一種情況下工作,但沒有在另一種情況下。 – Pablo 2010-10-08 11:41:52