Reputation: 1094
I'm trying to add the point's name, which is a virtual attribute, to my json requests.
The problem is that I need the language_id of the user to get the correct name in the database.
I can't find any snippet allowing to call a method with a parameter in a "as_json overwrite".
This my current code :
# Adds the name of the point when query is json
def as_json(options={})
super.as_json(options).merge({:name => name(language_id)})
end
# Returns the name of the point regarding the column in use in this project.
def name(language_id)
@name ||= get_point_name(language_id)
end
I get either :
What is working, is when I replace language_id by the value it is supposed to be (i.e the integer 80). In this way, I get my point's name in the correct language...
I've also tried to call a the global method current_language that I usually use in my controllers/views, but it seems I can't call such a global method from the model :-(
Thx for helping
Upvotes: 1
Views: 512
Reputation: 2297
I think you should go with a custom serializer if you are doing lots of this stuff, see ActiveModel::Serializers.
However, you could include the method that returns the correct name in the #as_json override.
super({:methods => [:name]}.merge(options))
Upvotes: 2