无法让控制器使用params hash

时间:2012-07-23 10:29:32

标签: ruby-on-rails model controller

我有has_many关联,想要获取用户网站和来自控制台用户。网站给我列出了所有网站,但是当我在控制器中尝试时:

     def index
      @websites = User.find(params[:user_id]).websites
    end

给我错误:编辑

     Rendered C:/Ruby193/lib/ruby/gems/1.9.1/gems/actionpack-3.2.2/lib/action_dispatch/middleware/templates/rescues/_trace.erb (3.0ms)
    Rendered C:/Ruby193/lib/ruby/gems/1.9.1/gems/actionpack-3.2.2/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.0ms)
   Rendered C:/Ruby193/lib/ruby/gems/1.9.1/gems/actionpack-3.2.2/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (99.0ms)
         ←[1m←[36mUser Load (2.0ms)←[0m  ←[1mSELECT `users`.* FROM `users` WHERE `users`.`id` =67 LIMIT 1←[0m
    Completed 500 Internal Server Error in 2ms
 ActiveRecord::RecordNotFound (Couldn't find User without an ID):
 app/controllers/websites_controller.rb:10:in `index'

但我已登录并且确实拥有id = 67的用户:

          User.find(67)
         => #<User id: 67, first_name: "admin", ...

在我看来:

 <% @websites.each do |website| %>
 <%= website.name  %>  
   <%= website.url %> 
  <p> <%= website.category %>
  <%= website.language %> 
<%end%>

编辑。请在索引视图中检查params [:user_id],这并没有显示我的任何感觉:

        <%= params[:user_id]%>

为什么我会收到错误?

1 个答案:

答案 0 :(得分:1)

你从哪里获得params[:user_id]

你试过了吗?

def index
  @websites = User.find(params[:id]).websites
end

您需要解释如何找到用户 你说你已经登录了,所以你有current_user吗?

def index
  @websites = current_user.websites
end

或部分执行:

def index
  @user = #find the user 
  @websites = @user.websites
end