未明确的方法“存储”时,它是什么?

时间:2012-01-04 09:33:31

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

我不明白为什么这样做。我有我的BusinessStore模型中定义的方法,然后我回到它的范围:

business_store.rb

class BusinessStore < ActiveRecord::Base
  attr_accessible :website, :business_name, :address, :phone_number, :online_store
  belongs_to :business
  has_many :user_prices
  attr_accessor :business_name
  validates_presence_of :address, :unless => :website?
  validates_presence_of :business_name
  validates_inclusion_of :online_store, :in => [true, false]

  def store
    if self.online_store
      "#{business_name} - #{website}"
    else
      "#{business_name} - #{address}"
    end
  end

  def business_name
    business.name if business
  end

  def business_name=(name)
    self.business = Business.find_or_create_by_name(name) unless name.blank?
  end
end

的user_data / index.html.erb

<% for user_price in @bought_today %>
   <%= number_to_currency(user_price.price) %>
   <%= truncate(user_price.product_name, :length => 62) %></td>
   <%= truncate(user_price.business_store.store, :length => 85) %></td> # here
   <%= user_price.purchase_date.strftime("%b %d, %Y") %></td>
<% end %>

然后我去页面并获得:

ActionView::Template::Error (undefined method `store' for nil:NilClass):

为什么这不起作用?

2 个答案:

答案 0 :(得分:4)

问题不在#storeBusinessStore未定义,而是您对user_price.business_store的调用正在返回nil,即当前{之间没有关联{ {1}}和user_price

如果您确定每个BusinessStore都属于user_price,您可能需要检查您的型号代码(我假设称之为)business_store并确保您你的协会在那里设立。此外,您可能需要确保将新UserPrice个对象与UserPrice相关联。这通常使用.build method

来完成
BusinessStore

这将创建一个与# In, for instance, UserPricesController#New @user_price = @business_store.user_prices.build 对象自动关联的新UserPrice模型。

答案 1 :(得分:-2)

看起来您的关联设置不正确。
 按照@ Alex的回答并报告错误是否仍然存在。