I don’t understand why its doing this. I have the method defined in my BusinessStore model and then I scope back to it:
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 %>
Then I go the page and get:
ActionView::Template::Error (undefined method `store' for nil:NilClass):
Why is this not working?
The problem isn’t that
#storeis undefined inBusinessStore, but that your call touser_price.business_storeis returningnil, i.e. there is no association between the currentuser_priceand aBusinessStore.If you’re sure that every
user_priceshould belong to abusiness_store, you may need to check your model code for (what I assume is called)UserPriceand make sure you have your association set up there. In addition, you may need to make sure you’re associatiating newUserPriceobjects with aBusinessStore. This is commonly done using the.buildmethod:This creates a new
UserPricemodel automatically associated with the@business_storeobject.