Rails month_field数据类型

时间:2014-12-11 15:11:02

标签: ruby-on-rails ruby ruby-on-rails-4 types

我已在迁移文件

中为月份字段定义日期数据类型
t.date :month

并检查其在模型中的估值

validates :month, presence: true

以我的形式,

= f.month_field :month, class: "form-control"

但是我希望将数据保存在不保存的状态。当我为我的控制器调试时

params[:rent]
=> {"item"=>"Room", "charge"=>"100", "payment_date(1i)"=>"2014", "payment_date(2i)"=>"12", "payment_date(3i)"=>"11", "month"=>"2014-11"}

查看月份字段。我们有价值,但当我尝试创建新的记录

@rent = current_user.rents.new(rent_params)
=> #<Rent id: nil, item: "Room", charge: 100, payment_date: "2014-12-11 00:00:00", month: nil, user_id: 1, created_at: nil, updated_at: nil>

月份字段为零。这是为什么?

我的控制器代码是

 def paid
    @rent = current_user.rents.new(rent_params)
    if @rent.save 
      redirect_to payment_url(@rent)
    else
      render "pay"
    end
  end

  private

  def rent_params
    params.require(:rent).permit(:item, :charge, :payment_date, :month)
  end

我错了吗?

1 个答案:

答案 0 :(得分:0)

amenzhinsky是对的,但要扩展解决方案:

如果您只关心月份的数量,请在迁移中进行更改:

t.date, :month

t.integer, :month

然后在表单中使用select_month

或者您可以手动执行

select_tag('name',options_for_select([['January',1],['February',2],...]))