Wes Foster
Wes Foster

Reputation: 8900

Re-coding, can't use helper method in model

What is a better (proper) way to code this according to MVC? Here's the situation:

I have a collection_select in my form, and it works fine, however I'm wanting to do something like this (note the text of the option, the 4th arg)

#Form.html.haml
= form_for(@payment) do |f|
 = f.collection_select(:invoice_id, Invoice.due, :id, :number + ' ' + money(:amount_due))

That won't work because as far as I know, you can't concat the symbols. So, I resorted to this:

#Form.html.haml
= form_for(@payment) do |f|
  = f.collection_select(:invoice_id, Invoice.due, :id, :number_with_amount_due)

#Invoice.rb
def number_with_amount_due
  "##{number} (#{money(amount_due)})"
end

Which would work if I wasn't trying to call a helper method in the Model.

So what should I do? It would be nice to be able to concat the select text in the views, but if not possible, how can I achieve what I'm trying to do while retaining proper MVC in Rails?

Upvotes: 0

Views: 81

Answers (1)

Anthony Alberto
Anthony Alberto

Reputation: 10395

Largely edited my answer as I got it wrong.

Using f.select, you'll be able to provide an Array containing exactly what you need. Assuming that Invoice.due returns your desired collection of Invoice

Here goes :

f.select(:invoice_id, Invoice.due.map {|i| ["#{i.number} #{money(i.amount_due)}", i.id]})

I think that collection_select can't achieve what you're trying to do, unless you add the helper containing money to your model.

Upvotes: 1

Related Questions