rails undefined方法,用于模型对象

时间:2012-05-16 02:34:59

标签: ruby-on-rails undefined

我的模型出现了一个非常奇怪的错误。

我的观看代码有:

Pickup by: <%= link_to Trip.find_by_pickedpost_id(post).volunteer.name, Trip.find_by_pickedpost_id(post).volunteer %>

但无法呈现页面。它显示:

NoMethodError in Posts#index

Showing /Users/rails_projects/pickup/app/views/posts/_post.html.erb where line #31 raised:

undefined method `volunteer' for nil:NilClass
Extracted source (around line #31):

28:                 </div>
29:             <% else %>
30:             
31:                 Pickup by: <%= link_to     Trip.find_by_pickedpost_id(post).volunteer.name, Trip.find_by_pickedpost_id(post).volunteer %>
32:             <% end %>
33:         <% end %>
34:     </li>
Trace of template inclusion: app/views/posts/index.html.erb



Application Trace | Framework Trace | Full Trace
app/views/posts/_post.html.erb:31:in   `_app_views_posts__post_html_erb___3981341078159890289_70243818995260'
app/views/posts/index.html.erb:5:in `_app_views_posts_index_html_erb__1562091740607633290_70243844957440'

在rails控制台中,我试图毫无问题地调用志愿者方法:

1.9.2-p290 :016 > Trip.find_by_pickedpost_id(post11)
Trip Load (0.3ms)  SELECT "trips".* FROM "trips" WHERE "trips"."pickedpost_id" = 11 LIMIT 1
 => #<Trip id: 10, pickedpost_id: 11, volunteer_id: 30, created_at: "2012-05-12 16:49:50",   updated_at: "2012-05-12 16:49:50"> 

1.9.2-p290 :017 > Trip.find_by_pickedpost_id(post11).volunteer.name
Trip Load (0.3ms)  SELECT "trips".* FROM "trips" WHERE "trips"."pickedpost_id" = 11 LIMIT 1
User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 30 LIMIT 1
 => "Ari Runte" 

实际上不仅是志愿者方法,我试图在trip对象上调用的所有方法都会产生一个未定义的方法错误,甚至是Trip.find_by_pickedpost_id(post11).id

我尝试渲染Trip.find_by_pickedpost_id(post),并且页面渲染了trip文件。

Pickup by: #<Trip:0x007fc5d4866608>

可能是什么问题?

添加一些观察结果:

当我将代码更改为

<%= link_to Trip.find_by_pickedpost_id(post).some_invalid_method, ....%>,

页面呈现

undefined method `some_invalid_method' for #<Trip:0x007fc5d6ec8fd0>

比较
undefined method `volunteer' for nil:NilClass

为什么当方法实际合法时页面为trip对象呈现“Nil”?

由于

0 个答案:

没有答案