【问题标题】:Rails 4 : Saving value as JSON string object/array in PostgreSQLRails 4:在 PostgreSQL 中将值保存为 JSON 字符串对象/数组
【发布时间】:2016-12-01 01:11:31
【问题描述】:

我在表“配置”中有 1 个名为“message_notification”的列。我想在此列中生成保存结果为 JSON 对象:

message_notification: [
  {
    "alert" : "how are you doing today?"
  },
  {
    "alert" : "where have you been today?"
  }
]

对于表格,我使用

<%= simple_form_for(@configuration) do |f| %>
  Alert 1: <%= check_box_tag "configuration[message_notification][][alert]", 'how are you doing today?' %><label>Alert 1</label><br/>
  Alert 2: <%= check_box_tag "configuration[message_notification][][alert]", 'where have you been today?' %><label>Alert 2</label><br/>
  <%= f.submit %>
<% end %>

如何做到这一点?

[更新]

以上代码将解析为 ruby​​ 哈希(而不是 JSON)

我的控制器

@configuration.message_notification = {
  alert: params[:message][:alert]
}.to_json

结果:

message_notification: [
  {
    "alert" => "how are you doing today?"
  },
  {
    "alert" => "where have you been today?"
  }
]

[更新 2]

在控制台中:

=> a = value.message_notification
=> "[{\"alert\"=>\"alert1\"}, {\"alert\"=>\"alert2\"}]"
=> puts a
=> [{"alert"=>"alert1"}, {"alert"=>"alert2"}]
=> nil

【问题讨论】:

  • 你做得很好,有什么问题?
  • @AnujDhanju 我已经更新了我上面的问题
  • 您可以在require 'json' 上使用to_json hash
  • @Sravan 是的,我在我的控制器中做到了这一点.. 但仍然产生 =&gt;.. 请参阅上面的更新
  • 检查,puts { 'alert' =&gt; params[:message][:alert] }.to_json

标签: ruby-on-rails json ruby ruby-on-rails-4


【解决方案1】:

您可以使用 to_jsonruby hash 转换为 JSON object

只需在您的controller 中添加require 'json'

params = {"utf8"=>"✓", "_method"=>"new", "authenticity_token"=>"txroAHF2+YZOrm48DtBZdVqKzxLYyHFq4+GWQFnM6kNldXgRZJMPv0yfj‌​0/tfZVpuVvh39UVX4Fb66FNkkCZqA==", "message"=>{"name"=>"Dan Murphy Roundabout Test", "company"=>"transtech", "location_id"=>"", "message_notification"=>[{"alert"=>"alert1"}, {"alert"=>"alert2"}], "commit"=>"save", "controller"=>"message", "action"=>"create", "id"=>"1717"}}

由于你的params object在上面,根据你的要求你可以使用,

params['message']['message_notification'] = (params['message']['message_notification'].to_json)

这会将参数中的message_notification 转换为json object,并存储在数据库中。

【讨论】:

  • 我不清楚params['message']['message_notification'] = (params['message']['message_notification'].to_json) 的确切位置。
【解决方案2】:

这就是我所做的。

  def resource_params
    params.require(:appointment_modules_dataset_intake).permit(
      :appointment_id,
      :main_issue,
      :cvf
    ).tap do |p|
      p[:cvf] = JSON.parse(p[:cvf]) # This is the significant line
    end
  end

【讨论】:

    猜你喜欢
    • 2015-04-28
    • 2015-11-30
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 2023-03-07
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多