【问题标题】:"Category(#2203433720) expected, got String(#2155957040)" Collection_select returning string instead of integer“类别(#2203433720)预期,得到字符串(#2155957040)”Collection_select返回字符串而不是整数
【发布时间】:2014-08-01 02:18:45
【问题描述】:

我有两个模型“事件”和“类别”。事件模型具有属于“类别”的整数类型“类别”。类别模型有 key:value 存储这些类别如 1:医疗 2:健康 3:食品等。

class Event < ActiveRecord::Base
 belongs_to :category
end

class Category < ActiveRecord::Base
  has_many :events, foreign_key: "category"
end

我的架构是:

create_table "categories", force: true do |t|
 t.string   "name"
 t.datetime "created_at"
 t.datetime "updated_at"
end

create_table "events", force: true do |t|
 t.string   "name"
 t.integer  "category"
 t.datetime "created_at"
 t.datetime "updated_at"
end

我正在使用简单的表单,也许这是我出错的地方,但我返回了正确的值,但只是作为一个字符串。例如,如果我从下拉列表中选择了医疗,它将返回正确的“1”,但只是作为字符串而不是所需的整数。

/视图/事件

<%= f.input :category, as: :select, collection: Category.all, include_blank: "Select a category..." %>

我的下拉菜单正确显示并返回正确的值,但作为字符串而不是整数。有没有最好的方法来解决这个问题?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    您应该有f.input :category_id,因为这是您提交的内容,是您选择的类别的 ID,而不是类别本身。

    【讨论】:

    • 这是在我的“事件”视图中。我没有属性:category_id。 :category 应该和我设置的一样,对吗?
    • 这很奇怪,因为我进入了我的架构并更改了 Event.category => Event.category_id 并在 MVC 中进行了更改,它似乎很奇怪。是否有某种我没有遵循的 Rails 命名约定?
    • 是的,belongs_to 关联的默认外键是(association name)_id - guides.rubyonrails.org/…
    猜你喜欢
    • 2018-11-16
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多