我有两个模型,post 和 book,通过第三个 kms 关联。
关联看起来像:
class Post < ActiveRecord::Base
attr_accessible :name, :year, :author, :book_ids
has_many :kms
has_many :books, through: :kms
end
class Book < ActiveRecord::Base
attr_accessible :name
has_many :kms
has_many :posts, through: :kms
end
class Km < ActiveRecord::Base
attr_accessible :count, :book_id, :post_id
belongs_to :book
belongs_to :post
def self.search(search)
if search
case type
when "Name of Book"
where('book.name ILIKE ?', "%#{search}%")
when "Name OF Post"
where('post.name LIKE ?', "%#{search}%")
end
else
scoped
end
end
end
这里_kms.html.erb
看起来像:
<%= form_tag list_km_path, :method => 'get', :id => 'kms_search' do %>
<p style="float:right;display:inline;">
<%= hidden_field_tag :direction, params[:direction] %>
<%= hidden_field_tag :sort, params[:sort] %>
<%= select_tag "fieldtype", options_for_select([ "Name of Book", "Name of Post"], "Name of Book"), :style => 'width:150px;' %>
<%= text_field_tag :search, params[:search], :style => 'width:200px;', :placeholder => "search..." %>
</p>
<% end %>
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered">
<thead>
<tr>
<th><%= sortable "book.name", "Name of Book" %></th>
<th><%= sortable "post.name", "Name of Post" %></th>
</tr>
</thead >
<tbody>
<% for km in @kms %>
<tr>
<td><%= km.book.name %></td>
<td><%= km.post.name %></td>
</tr>
<% end %>
</tbody>
</table>
这里kms_controller.rb
看起来像:
def index
@per_page = params[:per_page] || 10
@kms = Km.search(params[:search],params[:fieldtype]).order(sort_column + " " + sort_direction).paginate(:per_page => @per_page, :page => params[:page])
end
def sort_column
Km.column_names.include?(params[:sort]) ? params[:sort] : "book.name"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
问题1:
我想在表单 kms_search 上搜索书名和帖子名称,但是当我选择字段类型书名并在字段上输入书名以及帖子名称时,它不起作用并且没有响应。
问题2:
我想对书名和帖子名进行排序,但出现错误:
PG::Error: ERROR: missing FROM-clause entry for table "book"
LINE 1: ...kms" ORDER BY book...
^
: SELECT "kms".* FROM "kms" ORDER BY book.name asc LIMIT 10 OFFSET 0
任何人都可以帮助我,我该如何解决我的问题?
谢谢。