2016-05-18 8 views
0

私はRails 4.2.3を使用しています。私のモデルでは、誰かに何かをさせるのにかかる時間を記録するフィールドがあります。これは、 "time_in_ms"というフィールドで、PostGresqlデータベースの整数です。私の質問は、私の形式では、私はミリ秒単位で入力する必要はありません、私はむしろ時間、分、秒から選択することです。これを私のRailsフォームでどのように設定するのですか?私のモデルには、そのようなフィールドがないので、私はきちんと書くにはどうすればよい...私の「collection_select」属性に入れて何Railsでは、ミリ秒フィールドを時、分、秒フィールドにマップするにはどうすればよいですか?

<div class="field"> 
    <%= f.label "Time" %> 
    <%= collection_select(:time_unit, :time_unit, @hours, {:prompt => true}) %> hrs 
    <%= collection_select(:time_unit, :time_unit, @minutes, {:prompt => true}) %> min 
    <%= collection_select(:time_unit, :time_unit, @seconds, {:prompt => true}) %> sec 
    <%= f.hidden_field :time_in_ms, :validate => true %> 
    </div> 

を知らないと、私のシングル「time_in_ms」に基づいてセレクタを事前移入します私のモデルのフィールド?

おかげで、 - あなたはあなたのコントローラを言及していないとしてデイブ

答えて

0

、私はTimersControllerとして、コントローラを想定しています。ビューの変更、およびコントローラのtimer_paramsメソッドを変更する必要があります。ここで

は、ビューのコードです:

<div class="field"> 
    <%= f.label "Time" %> 
    <%= select_tag('timer[hour]', options_for_select((1..12).to_a), {:prompt => 'Select Hour'}) %> hrs 
    <%= select_tag('timer[minute]', options_for_select((1..60).to_a), {:prompt => 'Select Minutes'}) %> min 
    <%= select_tag('timer[second]', options_for_select((1..60).to_a), {:prompt => 'Select Minutes'}) %> sec 
    <%#= f.number_field :time_in_ms %> 
    </div> 

、ここでは、コントローラ上のコードです:

def create 
    @timer = Timer.new(timer_params) 

    respond_to do |format| 
     if @timer.save 
     format.html { redirect_to @timer, notice: 'Timer was successfully created.' } 
     format.json { render :show, status: :created, location: @timer } 
     else 
     format.html { render :new } 
     format.json { render json: @timer.errors, status: :unprocessable_entity }  
     end 
    end 
end 


def timer_params 
    # Main Code goes here 
    params.require(:timer).permit(:time_in_ms) 
    params[:timer][:time_in_ms] = (params[:timer][:hour].to_i * 60 * 60 + params[:timer][:minute].to_i * 60 + params[:timer][:second].to_i) * 1000 
end 

私は検証の部分を残しています。クライアント側だけでなくサーバー側でも実装できます。

関連する問題