0

How can I make this MVC?

  class Product < ActiveRecord::Base
    validates :price, :presence => true

    def to_s
      "#{name} at #{number_to_currency(price)}"
    end

  end

I need to format price to a currency, but I can't use number_to_currency, because this is in the model. I could pass the view into this, but that doesn't feel very clean.

1
  • Does it need to be in the model? Where and how do you use this method? Commented May 8, 2013 at 14:30

2 Answers 2

2

A solution could be to define a ProductHelper module in app/helpers that implements the method you want, say product_name_with_price:

module ProductHelper
  def product_name_with_price(product)
    "#{product.name} at #{number_to_currency(product.price)}"
  end
end

and then in the view

<%= product_name_with_price(@product) %>
Sign up to request clarification or add additional context in comments.

4 Comments

I am using the .to_s in other models though (specifically to generate PDFs) So technically this never sees a view.
Well, if you ask how to make this M V C I suppose there's must be some kind of view. How do you generate the PDF?
I am using Prawn and the pdfs are getting sent out via email. So the client doesn't see them in the view.
Can you update your question adding the code you use to generate the pdf?
1

It is a violation of MVC, but you can have number_to_currency in the model if you wish. You just need to include ActionView::Helpers::NumberHelper.

  class Product < ActiveRecord::Base
    include ActionView::Helpers::NumberHelper
    validates :price, :presence => true

    def to_s
      "#{name} at #{number_to_currency(price)}"
    end

  end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.