我试图通过连接表从一个视图设置一个简单的搜索,并且作为一个新手,它不是很有效。我正在测试" books"我知道的是在主题栏的文章表中。
我的错误是: SQLite3 :: SQLException:没有这样的列:articles.subject:SELECT COUNT(*)FROM" keywords"在哪里(articles.subject LIKE'%books%')
我的架构是:
create_table "articles", force: true do |t|
t.string "title"
t.string "subject"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "articles_keywords", id: false, force: true do |t|
t.integer "article_id"
t.integer "keyword_id"
end
create_table "keywords", force: true do |t|
t.string "keyword"
t.datetime "created_at"
t.datetime "updated_at"
end
我的模特是:
class Keyword < ActiveRecord::Base
has_and_belongs_to_many :articles
accepts_nested_attributes_for :articles
def self.search_for(query)
where('articles.subject LIKE :query', :query => "%#{query}%")
end
我的控制器操作是:
def index
@keywords = params[:q] ? Keyword.search_for(params[:q]) : Keyword.all
end
我的观点操作是:
<%= form_tag "/", method: "GET" do %>
<%= text_field_tag :q %>
<%= submit_tag "Search" %>
<% end %>
<% if @keywords.any? %>
<% @keywords.each do |k| %>
<section>
<h3><b>Title</b>: <%= link_to k.keyword.title, keyword.title %></h3>
<p><b>Subject</b>: <%= keyword.subject%></p>
<% end %>
非常感谢您的帮助!
答案 0 :(得分:1)
您必须join
asocciated表(并且您可以使用范围):
class Keyword < ActiveRecord::Base
has_and_belongs_to_many :articles
accepts_nested_attributes_for :articles
scope :search_for, ->(query){ joins(:acticles).where('articles.subject LIKE :query', :query => "%#{query}%")}
end
简化复杂查询的宝石是squeel。通过
来讨论范围scope :search_for, ->(query){ joins{articles}.where{articles.subject =~ "%#{query}%"} }