Rya*_*Mes 1 enums ruby-on-rails ruby-on-rails-4
Rails 4.1提供了枚举.我查了一下它似乎在rails控制台上工作得很好.当我尝试通过我的控制器将数据从视图持久化到数据库时,我收到以下错误
"注册"不是有效的stream_type
以下是我的课
class Stream < ActiveRecord::Base
enum stream_type: { sales: 1, registration: 2, student: 3 }
belongs_to :course_presentation
has_many :subscriptions
has_many :contacts, :through => :subscriptions
validates :course_presentation_id, :stream_type, presence: true
end
Run Code Online (Sandbox Code Playgroud)
下面是我用来保存的代码
@stream = Stream.new(stream_params)
def stream_params
params.require(:stream).permit(:stream_type, :course_presentation_id, :is_active, :created_by_user_id, :updated_by_user_id)
end
Run Code Online (Sandbox Code Playgroud)
下面是视图代码
<%= f.label :stream_type %><br>
<%= f.collection_select :stream_type, StreamType.order(:name), :name, :name, include_blank: "<-- select -->" %>
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?我无法让它发挥作用
我想出了这一点,虽然答案并不完全满意.存储枚举值的下拉列表是大写的.例如"注册".当它试图保存它无法找到"注册",但它可以找到"注册".使用正确的案例保存枚举工作正常.
无论如何,我希望我可以使用对应于散列键的整数,但这似乎不起作用.
编辑
解决这个问题的另一种方法是......
params.require(:stream).permit(:stream_type, :course_presentation_id, :is_active, :created_by_user_id, :updated_by_user_id).tap do |w|
w[:stream_type] = w[:stream_type].to_i if w[:stream_type]
end
Run Code Online (Sandbox Code Playgroud)
我找到了另一篇文章
| 归档时间: |
|
| 查看次数: |
3118 次 |
| 最近记录: |