0

我是 Ruby on Rails 的初学者,所以我需要一点帮助。我最近开始阅读一个基本教程,它是使用 Scaffolding 教授的。我做了一个“客户端”模型: script/generate scaffold clients name:string ip_address:string speed:integer ... 在 clients_controller.rb 文件中,有一个名为 show 的方法:

  # GET /clients/1
  # GET /clients/1.xml
  def show
    @client = Client.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @client }
    end
  end

对于查询,我会去 localhost:3000/clients/{在此处输入 ID}。不是用 ID 搜索参数,我想用另一个值搜索,比如 ip_address 或 speed,所以我想我所要做的就是在“@client = Client.find(参数 [:id])"。但是,这不起作用,所以请有人告诉我如何使用另一个参数实现搜索。谢谢!

4

2 回答 2

1

由于事物的路由方式,这不起作用

当你做类似的事情时

map.resources :client(见config/routes.rb

当您使用脚手架时,这会自动发生。它根据您使用 id 的假设设置路由。

其中一条路线类似于

map.connect 'clients/:id', :controller => 'client', :action => 'show'

因此:id作为 URL 的一部分作为参数传递。

除非它们是不同的,否则您不应该将 IP 作为主要标识符 - 即便如此,它也会与 RESTful 路由混淆。


如果您希望能够按 IP 进行搜索,请为客户端修改您的索引操作

def index
  if params[:ip].present?
    @clients = Client.find_by_ip_address(params[:ip]);
  else
    @clients = Client.all
  end
end

然后你可以通过 ip 搜索到clients?ip=###.###.###

于 2010-06-25T02:46:04.513 回答
0

您的 routes.rb 文件中的这一行

map.connect 'clients/:id', :controller => 'client', :action => 'show'

意味着当调度程序使用 GET 方法接收格式为“clients/abcdxyz”的 URI 时,它将重定向它以显示具有值“abcdxyz”的方法,该方法在具有键:id 的参数哈希中可用。

编辑


由于您使用了脚手架,因此客户端资源将是 RESTful。这意味着当您向“/clients/:id” URI 发送 GET 请求时,您将被重定向到该特定客户端的显示页面。


在您的控制器代码中,您可以访问它

params[:id] # which will be "abcdxyz"

由脚手架搜索生成的 find 方法对主键即“id”列进行搜索。您需要将该语句更改为

@client = Client.find_by_ip_address(params[:id]) #find_by_column_name

或者

@client = Client.find(:first, :conditions => [":ip_address = ?", params[:id]])

:-)

于 2010-06-26T04:15:08.673 回答