samedi 4 novembre 2017

How to use currently logged in user varible in I18n locale file

I have a Rails app that I want to develop using both English and Japanese locales. Once the user logs in, the :flash displays in English "Logged in as " which is hard coded in to the sessions controller. In Japanese, the username would come first and the grammar would come after words ( としてログインされています), so I wanted to have different messages in the en.yml and jp.yml files.

The problem is that I can't get the logged in user's name to work in the yml files; instead of translating the variable to the currently logged in user, it merely displays the variable as text.

What am I doing wrong?

sessions_controller.rb:

class SessionsController < ApplicationController
  def new
  end

  def create
    @user = User.find_by(email: params[:session][:email].downcase)
    if @user && @user.authenticate(params[:session][:password])
      session[:user_id] = @user.id
      flash[:info] = t(:logged_in_as) # points to translator in .yml file
      # flash[:info] = "logged in as #{@user.name}" works but English only 
      redirect_to @user
    else
      flash[:danger] = t(:login_error) 
      render 'new'
    end
  end

  def destroy
    session[:user_id] = nil
    redirect_to root_path
  end
end`

jp.yml

ja:
  log_in_please: "ログインして下さい"
  logged_in_as: "%{user_name}  としてログインされています"
  login_error: "認証できません。入力された内容が正しくありません。"
  activerecord:
    models:
      users:
        name: user_name

EDIT: Here is the view for sessions:

<h1>Log in</h1>

<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for(:session, url: login_path) do |f| %>

      <%= f.label :email %>
      <%= f.email_field :email, class: 'form-control' %>

      <%= f.label :password %>
      <%= f.password_field :password, class: 'form-control' %>

      <%= f.submit "Log in", class: "btn btn-primary" %>
    <% end %>

    <p>New user? <%= link_to "Sign up now!", signup_path %></p>
  </div>
</div>

The model is called 'users' and the user name field is called (drum roll) 'name'.

It works if I refer to #{@user.name} in the controller but can I use the user's name in the yml file?

I have read http://ift.tt/NplSk3 quite a few times but still can't find how to refer to the currently logged in user.

Aucun commentaire:

Enregistrer un commentaire