У меня есть следующее выражение:
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
Каждый тест, кроме последнего. Разве это не ошибка?