I have two models:
class Product < ActiveRecord::Base
attr_accessible :amount, :name, :unit, :description, :stock, :limit
has_many :cart_rows
has_one :inquery
end
and
class Inquery < ActiveRecord::Base
attr_accessible :product, :text, :phone, :zip, :product_id, :state, :street, :city
belongs_to :product
end
In my index of Inqueries view I have:
<% @inqueries.each do |inquery| %>
<%= inquery.product.name %>
<%= inquery.text %>
<% end %>
And I get the following error: undefined method 'name' for nil:NilClass
What am I doing wrong? Does has_one behave differently than has_many?
I built an app based on the info you described here, and was able to reproduce your problem by having an Inquery record with nil values for product (also for text). You may wish to add better validators so that Inqueries with nils cannot be saved.
Here’s a paste from my rails console session:
As an aside, and now for some unsolicited advice: a field with the same name as a keyword, “text”, is a really bad idea. You might not shoot yourself in the foot today, but you will at some point. Consider renaming the text field to usertext or description or something like that.