0

我有两个模型,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

任何人都可以帮助我,我该如何解决我的问题?

谢谢。

4

1 回答 1

1

使用 SQL 查询时,将所有表名复数:

where('books.name LIKE ?', "%#{search}%")

问题2。

不知道这是否可行,但试试这样:

   <th><%= sortable "books.name", "Name of Book" %></th>
   <th><%= sortable "posts.name", "Name of Post" %></th>

def sort_column
    params[:sort].downcase == "posts.name" ? "posts.name" : "books.name"
end

并在您的索引操作中:

Km.search(params[:search],params[:fieldtype]).joins(:book).joins(:post).uniq.order(sort_column + " " + sort_direction)
于 2013-04-16T17:47:43.963 回答