我的问题是为db-table实现良好的枚举属性。 给出以下def类:
class PlayerLicense < ApplicationRecord
belongs_to :user
belongs_to :team
enum defaultDress: { black: 1, white: 2, :substitute => 3 }
validates :defaultDress,
presence: true,
inclusion: { in: defaultDresses.keys}
enum defaultPosition: { :defense => 1, :forwarder => 2, :center => 3, :goalie => 4 }
validates :defaultPosition,
presence: true,
inclusion: { in: defaultPositions.keys }
end
在浏览器提交(POST)之后,这是我的Rails服务器POST日志:
Started POST "/player_licenses" for 127.0.0.1 at 2018-07-11 19:12:34 -0400
Processing by PlayerLicensesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Gn4BmF4.......V1x50CYD0GknQJNQ==", "team_id"=>"7", "player_license"=>{"user_id"=>"6", "defaultDress"=>"2", "defaultPosition"=>"2"}, "commit"=>"assign this player to 'Smithfield guys' team"}
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 17], ["LIMIT", 1]]
Completed 401 Unauthorized in 6ms (ActiveRecord: 0.8ms)
ArgumentError ('2' is not a valid defaultDress):
activerecord (5.1.4) lib/active_record/enum.rb:139:in `assert_valid_value'
activerecord (5.1.4) lib/active_record/attribute.rb:67:in `with_value_from_user'
activerecord (5.1.4) lib/active_record/attribute_set.rb:54:in `write_from_user'
activerecord (5.1.4) lib/active_record/attribute_methods/write.rb:39:in `write_attribute'
activerecord (5.1.4) lib/active_record/attribute_methods/write.rb:20:in `__temp__4656661657c6474427563737='
activemodel (5.1.4) lib/active_model/attribute_assignment.rb:46:in `public_send'
activemodel (5.1.4) lib/active_model/attribute_assignment.rb:46:in `_assign_attribute'
activemodel (5.1.4) lib/active_model/attribute_assignment.rb:40:in `block in _assign_attributes'
activemodel (5.1.4) lib/active_model/attribute_assignment.rb:39:in `each'
activemodel (5.1.4) lib/active_model/attribute_assignment.rb:39:in `_assign_attributes'
activerecord (5.1.4) lib/active_record/attribute_assignment.rb:26:in `_assign_attributes'
activemodel (5.1.4) lib/active_model/attribute_assignment.rb:33:in `assign_attributes'
activerecord (5.1.4) lib/active_record/core.rb:337:in `initialize'
在此示例中,到目前为止,来自浏览器的参数都很好,然后enum.rb assert_valid_value获得正确的值(2),但类型错误(got:字符串,必须为:integer)。这就是assert_valid_value中出现ArgumentError的原因。
在Rails控制台中,一切正常,属性/值分配,验证,object.save / read正常运行。在db级上检查(在从rails控制台发出object.save之后)验证DB-Table中正确的数据记录。这到底是什么(帕拉姆斯演员?),有人可以帮忙,请提供一些有关原因和解决方案的想法吗?谢谢你,哈里。
答案 0 :(得分:0)
问题似乎出在您的表单实现上。而不是发送枚举键(字符串),而是发送枚举值(整数)。
而不是...
<%= f.select :defaultDress, PlayerLicense.defaultDresses ... %>
使用
<%= f.select :defaultDress, PlayerLicense.defaultDresses.keys ... %>