簡體   English   中英

如何使用ActiveRecord比較列?

[英]How can I use ActiveRecord to compare columns?

在我的應用程序中,用戶可以加入房屋。

Houses表中是整數類型的bedrooms列。

給定

h = House.new
h.users

我們可以看到已加入特定房屋的所有用戶。

一旦h.users == h.bedrooms ,我想從houses#index視圖中刪除那所房子。

HousesController的index操作當前如下所示:

  def index
    @houses = House.all
  end

House.rb

has_many :bookings
has_many :users, through: :bookings

我應該將@houses設置為什么才能獲得所需的結果?

添加計數器緩存以在房屋模型中計數用戶

然后在HousesController中

def index
    @houses = House.where("users_count < ?",bedrooms)
  end

這取決於關聯是如何定義的,那就是:有用戶和預訂之間的1對1的關系?

如果是這種情況,則可以使用:

class User
  has_many :bookings
  has_many :houses, through: :bookings
end

# column 'user_id', integer
# column 'house_id', integer
class Booking
  belongs_to :user
  belongs_to :house
end

# column 'bedrooms', integer
class House
  has_many :bookings
  has_many :users, through: :bookings


  def is_full?
    bedrooms <= bookings.count
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM