简体   繁体   English

如何在 Rails 上的 Ruby 中搜索

[英]How to search in Ruby on Rails

I have the three models:我有三个模型:

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

How can I obtain all travels that a user has joined in the past?如何获取用户过去加入的所有旅行? I did something like that:我做了这样的事情:

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

but i don't kwon how to correctly join the results.但我不知道如何正确加入结果。

First you need to fix the relationship首先你需要修复关系

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

Then you can simply search it using然后你可以简单地使用搜索它

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

This should work:这应该有效:

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

Try this in the console, and pay attention to the sql produced.在控制台试试这个,注意生产的sql。 That will show you possible errors.这将向您显示可能的错误。

The travels in the joins clause is the model name. joins 子句中的travels是 model 名称。 The travels in the where clause must be the literal database table name, which I just guessed. where 子句中的travels必须是文字数据库表名,我只是猜到了。

Seems to me you'd be better off using a has_and_belongs_to_many relations and a join table to join the User and Travel models as long as you're not including any additional information in the JoinedTravel model?在我看来,只要您不在 JoinedTravel model 中包含任何其他信息,您最好使用 has_and_belongs_to_many 关系和连接表来加入 User 和 Travel 模型?

https://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association 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

You could then see if a user has any travels:然后,您可以查看用户是否有任何旅行:

@user.travels.present?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM