Rails 请教关于 restful 的问题

xoxoj · 2012年04月14日 · 最后由 xoxoj 回复于 2012年04月15日 · 4219 次阅读

我想实现如下格式的 web 地址访问:

www.test.com/users/1

1 是表示用户的 uid,访问这个网址,显示出 uid 为 1 的用户信息。

然后我是这样设置路由的

TestSQL::Application.routes.draw do resources :users end

然后在 users_controller.rb 里,我写了如下代码

class UsersController < ApplicationController def index @kk = User.all @user = User.first @ipk = User.find(params[:uid]) end

def show

end

def new

end

def create

end

def edit

end

def update

end

def destroy

end

end

在 users 目录下的 index.html.erb 写了如下代码:

hello world!

<% @kk.each do |k| %> <%= k.unn %> <% end %>

<%= @ipk %>

<%= link_to user.unn, user %>

为什么当我在浏览器里输入一下地址时 http://localhost:3000/users/ 时,会报这个错误呢

错误如下:

ActiveRecord::RecordNotFound in UsersController#index

Couldn't find User without an ID

Rails.root: /Users/JasonJiang/ror/TestSQL Application Trace | Framework Trace | Full Trace

app/controllers/users_controller.rb:5:in `index'

Request

Parameters:

None

Show session dump

Show env dump Response

Headers:

None

当我输入http://localhost:3000/users/1 的时候,怎么又是显示 show.html.erb 里的内容啊,然后,我又测试了一下其他的参数http://localhost:3000/users/asdfad , http://localhost:3000/users/2323, 都是显示 show.html.erb 里的内容。。

不理解啊!

还有另外一点就是,我在 users 数据库表里,没有使用 id 作为主键,而是我使用了 uid 作为主键,会不会是因为这个问题啊?求解答!谢谢啦。

为什么当我在浏览器里输入一下地址时 http://localhost:3000/users/ 时,会报这个错误呢

你 index 里面的 params[:uid] 是空的,所以 User.find 报错。

当我输入http://localhost:3000/users/1 的时候,怎么又是显示show.html.erb里的内容啊,然后,我又测试了一下其他的参数http://localhost:3000/users/asdfad , http://localhost:3000/users/2323, 都是显示show.html.erb里的内容。。

不理解啊!

看完文档你就理解了。http://guides.rubyonrails.org/routing.html

还有另外一点就是,我在users数据库表里,没有使用id作为主键,而是我使用了uid作为主键,会不会是因为这个问题啊? 求解答! 谢谢啦。

这个如果你是现有数据库换 rails,你可能需要研究一下 set_primary_key。

class User
  set_primary_key :uid
end

如果这个 rails 项目是新项目 (TestSQL?) 而你又是 rails 新手,建议你不要走非主流路线还是老老实实用 id 可以省很多事。

好的,感谢你的帮助,我再多研究一下!谢谢啦

测试一下

@xoxoj

mian

ssssssdff







ss

需要 登录 后方可回复, 如果你还没有账号请 注册新账号