Even if you could do it, you should not. Which is also the reason why you cannot: In MVC, the view is merely a presenter. All it should (ideally) do is "put this value there, put this value there, put this value there and put this there" and so on. In Rails, for pragmatic reasons, we often break this; we fetch stuff from the database, access related data and so on. But "writing data" is such a violation that it simply is not possible¹.
Since a view has no functionality and cannot have side-effects¹ (setting a language is a side-effect) what you need is to push the change through the common MVC flow.
The long version would be (left out most internals):
Customer-browser -> request -> router -> controller#action -> models -> controller#action -> views -> controller#action -> response -> Customer-browser
So, what you need, is to trigger a request-response when the language changes. There are many strategies from here, depending on your case. Ranging from redirecting from fr.example.com to nl.example.com to setting per-user-record language preferences in the database. Many are covered in the official rails guides on internationalisation.
But in all cases, you need to trigger a request-response cycle, so that the controllers get the chance to re-render the views with the "new" locale.
The easiest way to trigger a request-response is with a simple link.
_language_switcher.erb
<%= link_to(url_for(query: { lang: 'NL' }), "NL") %>
<%= link_to(url_for(query: { lang: 'FR' }), "FR") %>
The page is then re-requested with an appended ?lang=NL if a person clicked on the "NL" link.
You then want to handle the language setting before anything is rendered, based on that query argument. And do that in a generic place. E.g. the application_controller.rb:
class ApplicationController < ActionController::Base
before_action :set_locale
private
def set_locale
I18n.current_locale = locale_from_query || default_locale
end
def locale_from_query
params[:lang]
end
def default_locale
:nl
end
end
The actual implementation needs some additional work, though. So that you can avoid someone passing e.g. lang=bogus or lang= or lang=en. And you'd need additioanal work if you want to redirect to subdomains, work through caching layers and so on. But the basics is this simple.
¹ As discussed in the comments, technically this is possible, since ERB (or slim) will just run any code you embed in it. What you cannot do is i) trigger a side-effect and have that show up in the view as this question asks. Or ii) have side-effects-in-views and sane, stable and secure app at the same time.
selected_language.