1

我的模型有一个非常奇怪的错误。

我的视图代码有:

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.find_by_pickedpost_id(post11).id

我试图渲染 Trip.find_by_pickedpost_id(post) 并且页面渲染旅行对象很好。

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

当方法实际上合法时,为什么页面会为行程对象呈现“Nil”?

谢谢

4

0 回答 0