[英]Can I get search results on pg_search from a user_id?
我的书中有一个使用pg_search的模型,在搜索中,我希望能够按用户名搜索书。 在我的book.rb模型中,我具有以下内容:
include PgSearch
pg_search_scope :search, :against => [:title, :age, :story_types, :slug, :synopsis, :body, :user],
associated_against: {
user: [:name]
},
using: { tsearch:{ dictionary: "english" } }
belongs_to :user
belongs_to :gallery
has_many :stories
has_many :images
has_many :reviews
has_and_belongs_to_many :schools, join_table: "books_schools"
accepts_nested_attributes_for :user
accepts_nested_attributes_for :gallery, :allow_destroy => true
accepts_nested_attributes_for :schools, :allow_destroy => true, :reject_if => :find_school
accepts_nested_attributes_for :images, :allow_destroy => true
def self.text_search(query)
if query.present?
where("title @@ :q or synopsis @@ :q or age @@ :q", q: query)
else
scoped
end
end
上面的代码对我在书中拥有的任何内容都适用,但是我需要做的是找到与该书相关联的用户名。 在我的架构中,我在books表上附加了user_id,并且可以在我的视图和模型中使用以下内容获取该书的用户详细信息: @book_author = User.where("id = '#{@book.user_id}'")
然后要获得名称,我就做<%= book.user.name %>
我知道有人可能会说这很奇怪,但是保存书籍的方式对我来说是合乎逻辑的。
任何人都可以尝试并帮助我开始在正确的位置进行搜索。 我相信它很简单,但是很难引起注意。
干杯
使用委托http://apidock.com/rails/Module/delegate在book.rb中添加以下行
delegate :name, :to => :user, ;prefix => true
在视图中,请遵循<%= @book.user_name %
>。 @book是一个Book实例
即使您不想使用委托,也可以简单地执行<%= @book.user.name %
>
如果您提交控制器并查看代码以获取更多帮助,那就太好了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.