如何编写活动记录查询

时间:2017-02-23 02:17:14

标签: sql ruby-on-rails-3 sqlite rails-activerecord active-record-query

我在这个问题的背景下有三个模型:

class ClearanceBatch < ActiveRecord::Base    
    has_many :items
    belongs_to :user
end

class Item < ActiveRecord::Base

  belongs_to :style
  belongs_to :user
  belongs_to :clearance_batch
  validates :id, :uniqueness => true
end

class User < ActiveRecord::Base

    has_many :items, dependent: :destroy
    has_many :clearance_batches, dependent: :destroy    
    enum role: {staff: 0, vendor: 1, admin: 2}           

end

架构:

    create_table "clearance_batches", force: :cascade do |t|
        t.datetime "created_at"
        t.datetime "updated_at"
        t.boolean  "status",     default: false
        t.string   "boughtby",   default: ""
        t.integer  "user_id"
      end

      add_index "clearance_batches", ["user_id"], name: "index_clearance_batches_on_user_id"

      create_table "items", force: :cascade do |t|
        t.string   "size"
        t.string   "color"
        t.string   "status"
        t.decimal  "price_sold"
        t.datetime "sold_at"
        t.integer  "style_id"
        t.datetime "created_at"
        t.datetime "updated_at"
        t.integer  "clearance_batch_id"
        t.integer  "user_id"
      end



 create_table "users", force: :cascade do |t|
        t.string   "email",                  default: "", null: false
        t.string   "encrypted_password",     default: "", null: false
        t.string   "reset_password_token"
        t.datetime "reset_password_sent_at"
        t.datetime "remember_created_at"
        t.integer  "sign_in_count",          default: 0,  null: false
        t.datetime "current_sign_in_at"
        t.datetime "last_sign_in_at"
        t.string   "current_sign_in_ip"
        t.string   "last_sign_in_ip"
        t.datetime "created_at",                          null: false
        t.datetime "updated_at",                          null: false
        t.integer  "role",                   default: 0
      end

我想在当前登录用户(主要是供应商)的批次中找到状态为“clearanced”的所有项目,并从控制器到我的视图循环获取其详细信息

任何人都可以帮我解决有效的记录查询吗?请! :)

我认为SQLite查询将是:

Select I.id  from clearance_batches C INNER JOINS Items I on C.id = I.clearance_batch_id where C.user_id = "1"  and I.status = "clearanced"

(如果1是当前用户,请记住我只允许角色供应商的用户成为clearance_batch表中的用户)

1 个答案:

答案 0 :(得分:0)

(1)查询:

Items.where(status: "clearanced")
     .joins(:clearance_batches)
     .where(clearance_batches: {user_id: current_user})

(2)控制器:

@clearanced_items = query(1)

(3)查看:

<% @clearanced_items.each do |c_item| %>
    ...
<% end %>