LearningRoR
LearningRoR

Reputation: 27222

Undefined method "store" when clearly it is?

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?

Upvotes: 0

Views: 1056

Answers (2)

Jatin Ganhotra
Jatin Ganhotra

Reputation: 7035

Looks like your associations are not set correctly.
Follow through @Alex's answer and report back if the error is still there.

Upvotes: -2

Alex
Alex

Reputation: 9471

The problem isn't that #store is undefined in BusinessStore, but that your call to user_price.business_store is returning nil, i.e. there is no association between the current user_price and a BusinessStore.

If you're sure that every user_price should belong to a business_store, you may need to check your model code for (what I assume is called) UserPrice and make sure you have your association set up there. In addition, you may need to make sure you're associatiating new UserPrice objects with a BusinessStore. This is commonly done using the .build method:

# In, for instance, UserPricesController#New
@user_price = @business_store.user_prices.build

This creates a new UserPrice model automatically associated with the @business_store object.

Upvotes: 4

Related Questions