views:

55

answers:

2

Is it possible to override the to_sentence method just for one model in my rails application?

More generally, how do I modify methods for an Array of my models?

A: 

You can just defined *to_sentence* in that particular model.

class Model < ActiveRecord::Base

  def to_sentence

  end

end

When you are manipulating the results of a query in AR, each element of the array is an instance of your model class, so will automatically have all the methods and properties. The array itself will have all of the methods of the built-in Array and Enumerable classes (plus a few extras from AR). You can override or extend theses classes as well.

Toby Hede
He wants to override `ActiveSupport::CoreExtensions::Array::Conversions#to_sentence`. Adding `to_sentence` to his ActiveRecord model won't achieve that.
Jimmy Cuadra
Toby,Thanks for your answer but probably I should have given a real example. What I'm trying to achieve is to have the tags of my CMS always listed with commas when using to_sentence, overriding the default behavior (with "and" for last entry).I know how to override the behavior for the single model (I overrided "to_s" in the tag so that I get its name, not the #<Tag:0x56c9628> thing :) ), but I don't know how to do such a thing on Arrays of tags, and I would like to have if only for tags.
mirithil
@mirithil - In that case why not just do `myArray.join(',')`?
Jimmy Cuadra
I want a more "DRYish" way for that :) I want to set the format in just one place so that all Arrays consisting of tag objects output the same way. Any other solution is welcome!
mirithil
A: 

As you can imagine I'm quite the noob both on Rails and Stackoverflow, but I'm trying to get it right :)

I've simply created a helper on applcation_helper.rb, that I can call in views whenever I need. Do you think that's the way to go, or is there a better way than that?

Anyways, I'm still curious to know if there's a way to override Array methods for Array containing a specific class/model :)

mirithil