【问题标题】:Rails serializing cannot insert valueRails 序列化无法插入值
【发布时间】:2017-11-26 21:36:20
【问题描述】:

我创建了迁移

add_column :users, :read_post_id, :integer

添加到用户模型

serialize :read_post_id  , Array

编辑: 如果我使用

<%=  User.find(current_user.id).read_post_id << 3 %>

我得到一个输出 [3]。但是这个值只是暂时的,不会被保存。如何保存? 我读了Rails serialized integer attribute in params, but not saving into model instance 这表示序列化属性不能是整数。改成文字了。 之后

<%=  User.find(current_user.id).read_post_id << ["3","5"] %>
<%=  User.find(current_user.id).read_post_id.count %>
<%=  User.find(current_user.id).save %>

我确实收到了一个输出 [["3", "5"]] 0 true

所以基本上什么都没有改变

【问题讨论】:

    标签: ruby-on-rails database oop sqlite


    【解决方案1】:

    您需要将read_post_id 列的数据类型更改为:text 而不是:integer

    为什么?因为 Active Record 使用 YAML 序列化文本列中的任何对象,而不是整数列。序列化的数据需要进入文本列而不是整数列。见 AR 文档:Saving arrays, hashes, and other non-mappable objects in text columns

    要更改列类型,请创建一个如下所示的新迁移文件:

    class ChangeReadPostIdColumnType < ActiveRecord::Migration
      def change
        change_column :users, :read_post_id, :text
      end
    end
    

    一个快速的不请自来的建议,如果 read_post_id 将被序列化为一个 id 数组,为什么不将其命名为 read_post_ids 以便于阅读?

    您可以使用下面的 sn -p 更改一个迁移文件中的列名和列类型:

    class ChangeReadPostIdColumnNameAndType < ActiveRecord::Migration
      def change
        change_column :users, :read_post_id, :text
        rename_column :users, :read_post_id, :read_post_ids
      end
    end
    

    【讨论】:

    • 你可能没有看到我的帖子编辑,但我做了从整数到文本的迁移,它仍然无法工作@esther
    • @John 好的,刚刚看到更新的帖子。您可以使用= 运算符代替&lt;&lt; 运算符吗?您还可以更新帖子以显示完整的控制台日志吗?最后,您可以使用current_user.read_post_id 而不是User.find(current_user.id).read_post_id
    • 试过 = 和
    • @John 哦,您是否尝试过在控制器或模型中而不是在视图/erb 文件中更新用户对象? &lt;%= 理想情况下应该只用于显示。你的current_user 方法是什么样的?我假设这会返回一个用户对象?
    • def current_user login_from_session || login_from_basic_auth 结束 @esther
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    • 2021-10-31
    • 2012-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多