簡體   English   中英

如何在 Rails 上的 Ruby 中搜索

[英]How to search in Ruby on Rails

我有三個模型:

class Joinedtravel < ApplicationRecord
    belongs_to :travel
    belongs_to :user   
end

class Travel < ApplicationRecord
    has_many :joinedtravels
    belongs_to :user
end

class User < ApplicationRecord
    has_many :joinedtravels
    has_many :travels
end

如何獲取用戶過去加入的所有旅行? 我做了這樣的事情:

@user = User.find(id)
@past_travels = Travel.where('travels.data < ?', DateTime.now)
@all_joinedtravels = @user.joinedtravels.travels 

但我不知道如何正確加入結果。

首先你需要修復關系

class Joinedtravel < ApplicationRecord
  belongs_to :travel
  belongs_to :user   
end

class Travel < ApplicationRecord
  has_many :users, through: joinedtravels
  has_many :joinedtravels
end

class User < ApplicationRecord
  has_many :travels, through: joinedtravels
  has_many :joinedtravels
end

然后你可以簡單地使用搜索它

User
  .find(id)
  .travels
  .where('travels.data < ?', DateTime.now)

這應該有效:

@user = User.find(id)
@past_joinedtravels = @user.joinedtravels.joins(:travels).where('travels.date < ?', DateTime.now)

在控制台試試這個,注意生產的sql。 這將向您顯示可能的錯誤。

joins 子句中的travels是 model 名稱。 where 子句中的travels必須是文字數據庫表名,我只是猜到了。

在我看來,只要您不在 JoinedTravel model 中包含任何其他信息,您最好使用 has_and_belongs_to_many 關系和連接表來加入 User 和 Travel 模型?

https://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

class Travel < ApplicationRecord
   has_and_belongs_to_many :user
end

class User < ApplicationRecord
   has_and_belongs_to_many :travels
end


@user = User.find(id)
@past_travels = Travel.where('travels.data < ?', DateTime.now)
@user_travels = @user.travels

然后,您可以查看用戶是否有任何旅行:

@user.travels.present?

暫無
暫無

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

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