RichardAE
RichardAE

Reputation: 2970

How to pass parameters to a symbol method call

I have a model concern which adds a method 't' allowing the models fields to be translated va I18n:

module  Translatable
  extend ActiveSupport::Concern

  def t(field_name)
    I18n.t("models.#{self.class.table_name}.#{translation_tag}.#{field_name}")
  end

Model:

class Model < ActiveRecord::Base
  include Translatable 

This works fine almost everywhere using:

@model.t(:name)

However I have a select field which uses this code to map the entries:

Model.all.order(name: :asc), :id, :name

And I want :name to use the translatable method instead. The below works, but I'm getting a missing argument error (quite clear why):

Model.all.order(name: :asc), :id, :t

However this doesn't work:

Model.all.order(name: :asc), :id, :t(:name)

What is the correct way to pass variables to methods when they are called as symbols?

Upvotes: 2

Views: 1222

Answers (1)

Pierre-Louis Gottfrois
Pierre-Louis Gottfrois

Reputation: 17631

You can't in this context.

Either create a dedicated method in your model to handle the name layout or use map before the select.

def i18n_name
  t(:name)
end

select Model.all.order(name: :asc), :id, :i18n_name

or

Model.all.map { |p| [ p.t(:name), p.id ] }

More information here

Note: I would not recommend placing i18n translations in your models, it should be in presenters. Have a look at Draper

Upvotes: 6

Related Questions