Search code examples
ruby-on-railsinternationalizationrenderpartialrails-i18n

Translate controller action_name in Rails 4


I want to translate my applications' views and as I'm using partial to render headers for each view like this:

<%=t "#{controller.controller_name.capitalize} #{controller.action_name}" %>

...I got stucked on translating them. How do I translate controller.action_name in custom translation file?

I've tried to access action names like this:

  parkings:
    index: "Parkings index"
    new: "New %{model}"

And many different variations of it, but every one failed. Could you help me?

This is a fragment of my controller:

  def new
    @parking = Parking.new
  end

  def create
    @parking = Parking.new(parking_params)

    if @parking.save
      redirect_to @parking, notice: t(:parking_created)
    else
      render action: 'new'
    end
  end

Thanks.


Solution

  • You should have the translations in your locale file. Add an underscore or hyphen to separate words in the key

    eg:

    # config/locales/en.yml
    en:
      parkings_index: Parkings index
      parkings_new: Parkings new page
    

    view file

    <%=t "#{controller_name}_#{action_name}" %>