Rails Simple_Form:如何显示国家的长名称 [英] Rails Simple_Form: How to show long name of the country

查看:160
本文介绍了Rails Simple_Form:如何显示国家的长名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  = simple_form_for @shop,:url => {:action => create},:html => {:id => 'new_shop'} do | f | 
= f.simple_fields_for:address,:html => {:multipart => true} do | o |
= o.input:country,:label => 国家

但是国家的名字正在以短格式保存在数据库中code> RU , FR AU 等等)。



我想知道,如何在视图中显示国家的完整名称?谢谢!
解决方案实际上是一个好主意,因为I18n在数据库中保存国家代码(不是长名称)。有了代码,你可以在后面得到如下的名字:

  class User< ActiveRecord :: Base 
#假设country_select和User属性`country_code`一起使用
#这将尝试翻译国名,如果没有翻译,使用默认的
#(通常是英文)可用
def country_name
国家= ISO3166 ::国家[country_code]
country.translations [I18n.locale.to_s] || country.name
end
end

检查: country_select:从国家/地区获取国名


I use simple_form gem to select country:

= simple_form_for @shop, :url => { :action => "create" }, :html => {:id => 'new_shop' } do |f|
  = f.simple_fields_for :address, :html => {:multipart => true} do |o|
    = o.input :country, :label => "Country"

But the name of the country is being saved in short format in the database (like RU, FR, AU, and so on).

I wonder, how can I show the full, long name of the country in the views? Thanks!

解决方案

Actually is a good idea saving the country code in the database (not the long name) because I18n. Having the code you can get later the name as follows:

class User < ActiveRecord::Base
  # Assuming country_select is used with User attribute `country_code`
  # This will attempt to translate the country name and use the default
  # (usually English) name if no translation is available
  def country_name
    country = ISO3166::Country[country_code]
    country.translations[I18n.locale.to_s] || country.name
  end
end

Check: country_select: Getting the Country Name from the countries gem

这篇关于Rails Simple_Form:如何显示国家的长名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆