找到在视图中执行变量时遇到问题的方法

时间:2012-02-20 21:27:55

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

我正在尝试使用User.find(@id).email在视图中显示用户的电子邮件,但它给了我一个错误couldn't find user without id,但我确定@id带有ID 3,因为显示<%=@id%> 3.另一件事如果我将id硬编码为User.find(3).email它会成功显示电子邮件。只有当我将@id变量作为参数放在find方法中时才会出现问题,这里发生了什么?提前谢谢你

查看/的 profile.html.erb

   <% @books.each do |book|%>
 <%=book.user_id %>      =>displays 3
 <%= User.find(book.user_id).email %>    =>cant find the id
 <%=User.find(3).email%>       =>works fine

错误

   Couldn't find User without an ID

    activerecord (3.1.0.rc8) lib/active_record/relation/finder_methods.rb:302:in   `find_with_ids'
    activerecord (3.1.0.rc8) lib/active_record/relation/finder_methods.rb:107:in `find'
    activerecord (3.1.0.rc8) lib/active_record/base.rb:441:in `find'
    app/views/deal/show.html.erb:83:in `block (2 levels) in     _app_views_deal_show_html_erb__772775201_99014040'
    activerecord (3.1.0.rc8) lib/active_record/relation.rb:15:in `each'
    activerecord (3.1.0.rc8) lib/active_record/relation.rb:15:in `each'
    app/views/deal/show.html.erb:80:in `block in  _app_views_deal_show_html_erb__772775201_99014040'
    activerecord (3.1.0.rc8) lib/active_record/relation.rb:15:in `each'
    activerecord (3.1.0.rc8) lib/active_record/relation.rb:15:in `each'
    app/views/deal/show.html.erb:13:in `_app_views_deal_show_html_erb__772775201_99014040'
    actionpack (3.1.0.rc8) lib/action_view/template.rb:144:in `block in render'
    activesupport (3.1.0.rc8) lib/active_support/notifications.rb:55:in `instrument'
   actionpack (3.1.0.rc8) lib/action_view/template.rb:142:in `render'
   actionpack (3.1.0.rc8) lib/action_view/renderer/template_renderer.rb:40:in  `block     (2levels) in render_template'n/finder_methods.rb:302:in   `find_with_ids'
    activerecord (3.1.0.rc8) lib/active_record/relation/finder_methods.rb:107:in `find'
    activerecord (3.1.0.rc8) lib/active_record/base.rb:441:in `find'
    app/views/deal/show.html.erb:83:in `block (2 levels) in     _app_views_deal_show_html_erb__772775201_99014040'
    activerecord (3.1.0.rc8) lib/active_record/relation.rb:15:in `each'
    activerecord (3.1.0.rc8) lib/active_record/relation.rb:15:in `each'
    app/views/deal/show.html.erb:80:in `block in  _.........................

1 个答案:

答案 0 :(得分:1)

确保@id是整数。如果是,我不明白为什么它不起作用。我只是在我自己的应用程序中尝试了完全相同的东西,它工作正常。

要确保@id是整数而不是字符串,请尝试以下操作:

<%= User.find(@id.to_i).email %>

如果这不起作用,请将您的确切错误复制/粘贴到此处,以便我们进一步了解问题。