Using jQuery and Ajax, when you select a parent category, child category candidates are displayed in a pull-down menu. However, only the child category was translated only in the default notation Vietnamese.
Example: Parent category => Question Child category => 1, Ngôn ngữ và văn hóa 2,Tập huấn kỹ thuật 3,Ứng dụng và thủ tục
The cause was that I didn't pass the locale to the controller when getting the child categories in Ajax.
category_pulldown.js
$("#parent").on("change", function () {
//Get ID from selected parent category
var id = document.getElementById("parent").value;
//Omission
$.ajax({
type: 'GET',
data: { parent_id: id }, //ID params[:parent_id]Put in and send
url: '/categories/pulldown', //In the categories controller, get the child category with the received ID
dataType: 'json',
}).done(function (children) { //Processing to display the acquired child category...
Although it is a partial excerpt, the locale was acquired by the following method.
application_controller.rb
before_action :set_locale
private
def set_locale
I18n.locale = locale
end
def locale
@locale ||= params[:locale] ||= I18n.default_locale
end
def default_url_options(options = {})
options.merge(locale: locale)
end
First, use the input tag to keep the current locale.
If you write type =" hidden "
as shown below, it will not be displayed on the screen even from the user's perspective.
hoge.html.erb
<input type="hidden" class="current_locale" value="<%= I18n.locale %>">
Then add locale: $ ('.current_locale'). Val ()
The translation languages for the parent and child categories have been unified.
category_pulldown.js
$("#parent").on("change", function () {
//Get ID from selected parent category
var id = document.getElementById("parent").value;
//Omission
$.ajax({
type: 'GET',
data: { parent_id: id, locale: $('.current_locale').val() }, //ID params[:parent_id]Put in and send
url: '/categories/pulldown', //In the categories controller, get the child category with the received ID
dataType: 'json',
}).done(function (children) { //Processing to display the acquired child category...
HTML is convenient because you can pass information from both Ruby and JavaScript: smiley:
Recommended Posts