【发布时间】:2011-08-01 18:08:54
【问题描述】:
我无法在外国模型的视图中渲染模型的属性。我认为这是一个嵌套属性问题,因为f.bike 有效,但f.bike.biketype 给出了未定义的方法错误。以下是我的错误和代码。任何帮助都会很棒。谢谢!
来自浏览器的错误:
NoMethodError in Carts#show
Showing /Users/willdennis/rails_projects/spinlister/app/views/carts/show.html.erb where line #4 raised:
undefined method `biketype' for nil:NilClass
Extracted source (around line #4):
1: <h2>Your Cart</h2>
2: <ul>
3: <% @cart.line_items.each do |f| %>
4: <li><%= f.bike.biketype %></li>
5: <% end %>
6: </ul>
views/carts/show.html.erb
<h2>Your Cart</h2>
<ul>
<% @cart.line_items.each do |f| %>
<li><%= f.bike.biketype %></li>
<% end %>
</ul>
cart.rb
class Cart < ActiveRecord::Base
has_many :line_items, :dependent => :destroy
belongs_to :user
accepts_nested_attributes_for :line_items
attr_accessible :bike_id, :name, :description, :size, :biketype, :price, :photo, :id, :address, :city, :state, :zip, :latitude, :longitude, :neighborhood
end
line_item.rb
class LineItem < ActiveRecord::Base
belongs_to :bike
belongs_to :cart
accepts_nested_attributes_for :bike, :cart
attr_accessible :name, :description, :size, :biketype, :price, :photo, :id, :address, :city, :state, :zip, :latitude, :longitude, :neighborhood
end
自行车.rb
class Bike < ActiveRecord::Base
has_many :line_items
attr_accessible :name, :description, :size, :biketype, :price, :photo, :id, :address, :city, :state, :zip, :latitude, :longitude, :neighborhood
end
carts_controller.rb
def show
@cart = Cart.find(params[:id])
end
【问题讨论】:
-
您确定数据库中的每个 line_item 都确实有关联的自行车吗?该错误表明其中一个自行车对象为 nil,如果 line_item 的 bike_id 为 nil 或引用不存在的自行车,这就是您所期望的。
-
我认为你可能是对的。当我检查我的数据库时,line_items 没有bike_id。这是我的 line_items_controller:
def create @cart = current_cart bike = Bike.find(params[:bike_id]) @line_item = @cart.line_items.build(:bike_id => bike)知道如何正确地将 bike_id 添加到 line_item 中吗?非常感谢!
标签: ruby-on-rails forms view models nested-attributes