Search code examples
ruby-on-railsformsvirtual-attribute

Rails 4: language select and virtual attributes


I'd like to have a small dropdown menu where users can select the website's language. For that, I have

<%= f.select(:lang, options_for_select([%w(中文 ch), %w(English en), %w(日本語 jp), %w(한국어 kr)], 'en')) %>

I'd like this to appear on all pages, and I don't think it's necessary to have that stored in a model, so I was thinking of making it with virtual attribtues.

I'm just a bit confused as to where/how I should make this virtual attribute :lang so that the dropdown appears on all pages and the language persists throughout the users' visit to the webpage. Should I make a getter/setter method in my application_controller.rb?

Thanks!


Solution

  • Something that appears on many pages that you only want to define once is often defined as a helper.

    app/helpers/application_helper.rb

    class ApplicationHelper
      def language_select
        form_for :language, :url => some_path do |form|
          form.select(:lang, options_for_select([%w(中文 ch), %w(English en), %w(日本語 jp), %w(한국어 kr)], 'en'))
        end
      end
    end
    

    In your views then:

    <%= language_select %>