为具有3个以上模型的关联创建SCOPE - Rails 4

时间:2016-03-12 14:33:46

标签: ruby-on-rails ruby

有人可以告诉我我的SQL查询出错了吗

  

我希望显示公司的表单列表,这些表单只接受   状态@company.forms.created_this_month.forms_accepted.count但是我   得到以下错误。我不确定我哪里出错 - 任何建议   非常感谢帮助

error in terminal:
2.1.2 :043 >   company.forms.created_this_month.forms_accepted
  Form Load (3.4ms)  SELECT "forms".* FROM "forms" INNER JOIN "adverts" ON "forms"."advert_id" = "adverts"."id" INNER JOIN "users" ON "adverts"."user_id" = "users"."id" WHERE "users"."company_id" = ? AND ("forms"."created_at" BETWEEN '2016-03-01 00:00:00.000000' AND '2016-03-31 22:59:59.999999') AND (status = 'Accepted')  [["company_id", 1]]
SQLite3::SQLException: ambiguous column name: status: SELECT "forms".* FROM "forms" INNER JOIN "adverts" ON "forms"."advert_id" = "adverts"."id" INNER JOIN "users" ON "adverts"."user_id" = "users"."id" WHERE "users"."company_id" = ? AND ("forms"."created_at" BETWEEN '2016-03-01 00:00:00.000000' AND '2016-03-31 22:59:59.999999') AND (status = 'Accepted')
ActiveRecord::StatementInvalid: SQLite3::SQLException: ambiguous column name: status: SELECT "forms".* FROM "forms" INNER JOIN "adverts" ON "forms"."advert_id" = "adverts"."id" INNER JOIN "users" ON "adverts"."user_id" = "users"."id" WHERE "users"."company_id" = ? AND ("forms"."created_at" BETWEEN '2016-03-01 00:00:00.000000' AND '2016-03-31 22:59:59.999999') AND (status = 'Accepted')


models
company.rb
has_many users
has_many :forms, through: :users

user.rb
belongs_to company
has_many adverts

advert.rb
belongs_to user
has_many forms

form.rb
belongs_to advert
scope :forms_accepted, -> {where(['status = ?', 'Accepted'])}
scope :created_this_month, -> { where(created_at: Time.now.beginning_of_month..Time.now.end_of_month) }


schema
  create_table "companies", force: true do |t|
    t.string   "companyname"
    t.string   "tel"
    t.string   "email"
  end

  create_table "users", force: true do |t|
    t.string   "email"
    t.string   "firstname"
    t.string   "lastname"
    t.integer  "company_id"
  end

  create_table "adverts", force: true do |t|
    t.string   "title"
    t.text     "content"
    t.integer  "user_id"
  end

  create_table "forms", force: true do |t|
    t.string   "firstname"
    t.string   "lastname"
    t.string   "email"
    t.string   "currentJob"
    t.string   "currentEmployer"
    t.integer  "advert_id"
    t.string   "status"
  end

1 个答案:

答案 0 :(得分:1)

而不是:

scope :forms_accepted, -> {where(['status = ?', 'Accepted'])}

使用

scope :forms_accepted, -> {where(status: 'Accepted'])}

正如您在第二个范围中使用的那样。