2014-10-16 93 views
-1

我有一个导轨形成我使用的是选择标记为帕拉姆:contratRails的选择 - 选择价值

这是我的代码

<%= f.label :contrat, "Type de contrat", class: "jobs-newtitles-two-half" %><br> 

<%= f.select(:contrat, [["CDI", 1], ["CDD", 2], ["Contrat de Travail Temporaire ou d’intérim", 3], ["Freelance", 4], ["Stage", 5]], {}, {class: "form-control form-two-half"}) %> 

当我在选择例如CDI选择为contrat列出并提交形式去表演的网页我有1代替CDI这是为什么

这是我的节目页面

Type de contrat: <%= @job.contrat %> 

而是获得类型德contrat:CDI我得到类型德contrat:1

+0

我真的不明白你的问题。你想要什么?提交后你想从选中的“CDI”中选择“1”吗? CDI是选中的文本而不是选定的值。 – 2014-10-17 05:05:06

+0

我已经解释了更多看现在的问题 – userails 2014-10-17 11:23:17

回答

1

您的代码:

<%= f.select(:contrat, [["CDI", 1], ["CDD", 2], ["Contrat de Travail Temporaire ou d’intérim", 3], ["Freelance", 4], ["Stage", 5]], {}, {class: "form-control form-two-half"}) %> 

这将节省1到数据库而不是"CDI",所以在你的显示页面上你有1

如果你想在你的展示页面上显示“CDI”,有很多方法可以做到这一点。


第一(不推荐,它可以打破一个干净的MVC方式)

添加到这个模型

class Job < ActiveRecord::Base 

def contrat_string 
    ## if string data type of contrat, you should quote e.g if contrat == "1" 
    if contrat == 1 
    "CDI" 
    elsif contrat == 2 
    "CDD" 
    elsif contrat == 3 
    "Contrat de Travail Temporaire ou d’intérim" 
    elsif contrat == 4 
    "Freelance" 
    else 
    "Stage" 
    end 
end 

end 

,并显示页面

Type de contrat: <%= @job.contrat_string %> 

上第二

Add方法到您的帮手

module ApplicationHelper 

    def contrat_to_s(contrat) 
    ## if string data type of contrat, you should quote e.g if contrat == "1" 
    if contrat == 1 
     "CDI" 
    elsif contrat == 2 
     "CDD" 
    elsif contrat == 3 
     "Contrat de Travail Temporaire ou d’intérim" 
    elsif contrat == 4 
     "Freelance" 
    else 
     "Stage" 
    end 
    end 

end 

,并显示页面上

Type de contrat: <%= contrat_to_s(@job.contrat) %> 

第三(推荐)

你可以把一个数组的定义/config/locales/your_language.yml

例如,如果你e使用英语en.yml

en: 
    contrat_strings: 
     1: CDI 
     2: CDD 
     3: Contrat de Travail Temporaire ou d’intérim 
     4: Freelance 
     5: Stage 

在你的帮手e。摹application_helper.rb

module ApplicationHelper 
    def contrat_selects 
    I18n.t(:contrat_strings).map { |key, value| [ value, key ] } 
    end 

    def contrat_views(value) 
    I18n.t(:contrat_strings)[value] 
    end 
end 

在显示页面

Type de contrat: <%= contrat_views(@job.contrat) %> 

在形式

<%= f.select :contrat, contrat_selects %> 

注:我已经测试。所有为我工作。

+0

感谢您的回答无论选择何种类型的对照我在显示页面中获得类型de对照:阶段 – userails 2014-10-17 12:12:36

+0

@userails:是否有效? ,我已经更新了我的答案,增加了另一种方式 – 2014-10-17 13:50:23

+0

第二种方法我仍然得到相同的结果。我还没有尝试第三种方法 – userails 2014-10-17 13:59:43

0

这应该工作:

<%= f.select :contrat, 
    options_for_select([["CDI", 1], ["CDD", 2], ["Contrat de Travail Temporaire ou d’intérim", 3], ["Freelance", 4], ["Stage", 5]]], params[:contrat]), 
    {}, { :class => 'form-control form-two-half' } %> 

How to make the f.select rails selected

+0

仍然得到相同的结果 – userails 2014-10-17 11:23:45