我有一个表单,用户可以输入一个日期(例如03/18/2014):
= f.text_field :purchase_date, class: "form-control", placeholder: "mm/dd/yyyy"
当用户为一个新的Inventory
对象提交表单时,我在Create操作中一直得到错误argument out of range
。然而,如果我已经有一个现有的对象,我尝试更新它,它工作得很好。奇怪的是,我的put没有在服务器日志中输出任何东西。
def create
puts "CREATE" # this line is not outputting anything
purchase_date = inventory_params["purchase_date"].blank? ? Date.today : Date::strptime(inventory_params["purchase_date"], "%m/%d/%Y")
@inventory = Inventory.create( name: inventory_params["name"],
purchase_price: purchase_price,
purchase_date: purchase_date,
serial: inventory_params["serial"].to_s,
description: inventory_params["description"].to_s,
product_type: inventory_params["product_type"].to_s,
current_location: inventory_params["current_location"].to_s,
vendor_id: inventory_params["vendor_id"],
team_id: current_team.id)
redirect_to inventories_path
end
def update
purchase_date = inventory_params["purchase_date"].blank? ? Date.today : Date::strptime(inventory_params["purchase_date"], "%m/%d/%Y")
@inventory.update_attributes( name: inventory_params["name"],
purchase_price: purchase_price,
purchase_date: purchase_date,
serial: inventory_params["serial"],
description: inventory_params["description"],
product_type: inventory_params["product_type"],
current_location: inventory_params["current_location"],
vendor_id: inventory_params["vendor_id"]
)
redirect_to inventory_path(@inventory)
end
private
def inventory_params
params.require(:inventory).permit(:purchase_price, :purchase_date, :name, :serial, :description, :product_type, :current_location, :vendor_id)
end
我也设置了CanCan,但我不认为它会影响它:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
can [:create, :show, :destroy, :edit, :update], User, id: user.id
can :create, Inventory
can [:index, :show, :destroy, :edit, :update], Inventory do |inventory|
user && (inventory.try(:team_id) == user.teams.first.id)
end
end
end
有人知道为什么当我尝试创建Inventory
的新实例时,我一直得到一个异常吗?
更新:看起来如果我用两位数的日期,它就坏了。例如,3/1/2014
工作,但3/11/2014
中断…
只是为了让你下次少写几行。你写的内容相当于@inventory =
Inventory.create(inventory_params.merge({team_id: current_team.id}))
和
@inventory.update_attributes(inventory_params)
另外,我发现了你的错误,你写的是03/18/14(这意味着2003-18-14),没有月18 !它不是用法语标准书写的:)
顺便说一下,如果你需要使用法语(或类似的)标准:请阅读http://guides.rubyonrails.org/i18n.html并下载所需文件:https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/fr.yml
Cancan与Rails 4.0发生了冲突。修复了这个问题:
load_and_authorize_resource :except => [:create]