我按照本教程解决了这个问题,但我必须进行一些更改才能使其适合我,因为我想要选择框。
http://railscasts.com/episodes/240-search-sort-paginate-with-ajax?view=asciicast
这是我的新代码:
index.html.erb
<form class="form-inline"
<p>
<select name="state_search" class="span2">
<option value="">Select a State</option>
<option>----------------</option>
<option>LA</option>
<option>MS</option>
<option>TX</option>
</select>
<select name="city_search" class="span2">
<option value="">Select a City</option>
<option>----------------</option>
<option>Mandeville</option>
<option>Covington</option>
</select>
<button type="submit" class="btn">GO</button>
</p>
</form>
<table class="table table-striped table-bordered span8 table-condensed"
id="articles_table" >
<thead class="header">
<tr>
<th>ID</th>
<th>Title</th>
<th>Description</th>
<th>Created_At</th>
</tr>
</thead>
<tbody>
<%= render @articles %>
</tbody>
_article.html.erb
<tr>
<td> <%= article_counter +1 %> </td>
<td> <%= article.Title %> </td>
<td> <%= article.Description %> </td>
<td> <%= article.Created_At %> </td>
</tr>
articles_controller.rb
def index
@articles = Article.state_search(params[:state_search]).city_search(params[:city_search]).page(params[:page]).limit(50).order('Created_At DESC')
respond_to do |format|
format.html # index.html.erb
format.json { render json: @articles }
format.js
end
end
articles.rb
def self.city_search(city_search)
if city_search
where('City LIKE ?', "%#{city_search}%")
else
scoped
end
end
def self.state_search(state_search)
if state_search
where('State LIKE ?', "%#{state_search}%")
else
scoped
end
end
首先,我创建了表格,其内容由部分呈现,就像在剧集中一样。然后我创建了两个选择框并给它们命名。一个是 state_search,另一个是 city_search。然后,我进入了articles.rb 并定义了这些名称。这与 railscasts 情节中的相同,只是我用我的名字替换了名字。接下来,我进入了articles_controller.rb 并将两个搜索添加到其中,就像在railscasts 集中一样。
之后,两个选择框完美地工作并排序/过滤了表格。
谢谢