【问题标题】:Is it bad to save data as ActionController::Parameters in a postgres DB with Rails?在使用 Rails 的 postgres 数据库中将数据保存为 ActionController::Parameters 是不是很糟糕?
【发布时间】:2015-04-03 13:41:00
【问题描述】:

情况是这样的。我使用 facebook 登录,并希望使用 postgres 数据库将朋友数组保存到我的 Rails 服务器中。

fb_friends 的参数是:

"fb_friends"=>[{"id"=>"1381984758791468", "name"=>"ios ipod"}]

Api控制器强参数: user_paramsfb_friends: [:id, :name]

在 User 模型中,我序列化了 fb_friends。

serialize :fb_friends

所有这些工作,但我注意到我的 fb_friend 的类类型是ActionController::Parameters,它的行为就像一个哈希。这是一件坏事吗?

在 Rails 控制台中,

u.fb_friends.first.class
 => ActionController::Parameters

u.fb_friends.first[:id]
 => "1381984758791468"

u.fb_friends.first[:name]
 => "ios ipod"

编辑:

忘记添加我的架构/迁移

迁移:

change_column :users, :fb_friends, :text

用户表的架构:

t.text     "fb_friends",      default: "{}"

【问题讨论】:

  • 为什么有人会投票结束这个? :(

标签: ruby-on-rails ruby facebook postgresql


【解决方案1】:

看起来它适合您,但更好的做法是创建一个名为 FacebookFriend 的模型,以便您的每个模型/数据库表只有一个用途。

FacebookFriend(id, user_id, facebook_friend_id, name, created_at, updated_at)

class User < ActiveRecord::Base
  has_many :facebook_friends
end

class FacebookFriend < ActiveRecord::Base
  belongs_to :user
end

如果您认为您的用户经常拥有共同的 FacebookFriends,您也可以建立“多通”关系。

【讨论】:

    【解决方案2】:

    除非您要反序列化它并将其用作 ActionController::Parameters 实例,否则您应该将其转换为标准哈希。对于加分,请在 postgres 中使用 hstore,您仍然可以搜索等。

    【讨论】:

    • 我将如何在代码中做到这一点?在 User.rb 模型类中?在控制器中?
    • 也许只是序列化 :fb_friends.to_json 或类似的东西.. 现在没有时间测试。无论哪种方式,to_a、to_h、to_json 都应该将其更改为更普通的数据类型。
    猜你喜欢
    • 2020-01-29
    • 2013-10-16
    • 1970-01-01
    • 2011-03-05
    • 2020-12-02
    • 1970-01-01
    • 2011-09-20
    • 2011-10-06
    • 2010-12-13
    相关资源
    最近更新 更多