0

我有 has_many 关联并希望获取用户网站,并且从控制台 user.websites 给了我所有网站的列表,但是当我在控制器中尝试时:

     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%>

EDIT.Tried 在索引视图中检查 params[:user_id] ,这并没有向我显示任何内容:

        <%= params[:user_id]%>

为什么我收到错误?

4

1 回答 1

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
于 2012-07-23T10:50:44.450 回答