【发布时间】:2011-04-18 06:35:30
【问题描述】:
大家好。我想知道如何在 rails 3 中使用命名范围进行简单搜索。我已经在控制台中成功完成了它,但我找不到任何使用视图的示例。
这是模型trap.rb的代码:
class Trap < ActiveRecord::Base
scope :by_date_entry, lambda { |arg| where(["traps.date_entry = ?",arg])}
scope :by_empcode, lambda { |arg| where(["traps.empcode = ?",arg])}
end
在控制器中traps_controller.rb:
class TrapsController < ApplicationController
# GET /traps
# GET /traps.xml
def index
@traps = Trap.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @traps }
end
end
# GET /traps/1
# GET /traps/1.xml
def show
@trap = Trap.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @trap }
end
end
# GET /traps/new
# GET /traps/new.xml
def new
@trap = Trap.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @trap }
end
end
# GET /traps/1/edit
def edit
@trap = Trap.find(params[:id])
end
# POST /traps
# POST /traps.xml
def create
@trap = Trap.new(params[:trap])
respond_to do |format|
if @trap.save
format.html { redirect_to(@trap, :notice => 'Trap was successfully created.') }
format.xml { render :xml => @trap, :status => :created, :location => @trap }
else
format.html { render :action => "new" }
format.xml { render :xml => @trap.errors, :status => :unprocessable_entity }
end
end
end
# PUT /traps/1
# PUT /traps/1.xml
def update
@trap = Trap.find(params[:id])
respond_to do |format|
if @trap.update_attributes(params[:trap])
format.html { redirect_to(@trap, :notice => 'Trap was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @trap.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /traps/1
# DELETE /traps/1.xml
def destroy
@trap = Trap.find(params[:id])
@trap.destroy
respond_to do |format|
format.html { redirect_to(traps_url) }
format.xml { head :ok }
end
end
end
在我看来index.html.erb:
<h2>Time Reconciliation Application for Payroll 1.0</h2>
<table>
<tr>
<th>Empcode</th>
<th>Date entry</th>
<th></th>
<th></th>
<th></th>
</tr>
<% @traps.each do |trap| %>
<tr>
<td><%= trap.empcode %></td>
<td><%= trap.date_entry %></td>
<td><%= link_to 'Show', trap %></td>
<td><%= link_to 'Edit', edit_trap_path(trap) %></td>
<td><%= link_to 'Destroy', trap, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New Trap', new_trap_path %>
我想放一个搜索文本框,用户可以在其中输入index.html.erb 中的employee_code 或date_entry。我使用 meta_search 和 meta_where 做了类似的事情,但我更喜欢使用 named_scope 但我不知道如何使用视图和控制器来显示它。我的模型 trap.rb 中的代码正在我的控制台上运行。我只是不知道如何让它出现在视图中。请帮忙...
【问题讨论】:
标签: ruby-on-rails-3 activerecord scope named-scope