【问题标题】:How to write the active record query如何编写活动记录查询
【发布时间】:2017-02-23 02:17:13
【问题描述】:

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

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

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

谁能帮我解决活动记录查询?请! :)

我认为的 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 是当前用户,请记住,我只允许角色供应商的用户成为 clear_batch 表中的用户)

【问题讨论】:

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


    【解决方案1】:

    (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 %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-27
      • 2016-01-08
      • 1970-01-01
      • 2021-06-22
      • 2021-10-30
      • 2015-10-27
      • 1970-01-01
      相关资源
      最近更新 更多