【问题标题】:Adding nested json in tables - rails在表中添加嵌套 json - rails
【发布时间】:2018-09-13 06:38:29
【问题描述】:

我是 ruby​​ on rails 的新手,我正在尝试将嵌套的 json 存储在表中。

 json: 
 articles: {
  title: "abc",
  text: "a",
  address: {
    flat: "abc",
    city: "bang"
   }
  } 

Migrations:
 class CreateArticles < ActiveRecord::Migration[5.2]
   def change
     create_table :articles do |t|
       t.string :title
       t.text :text
       t.string :address

       t.timestamps
     end
  end
 end

class CreateAddresses < ActiveRecord::Migration[5.2]
  def change
    create_table :addresses do |t|
      t.string :flat
      t.string :city

      t.timestamps
   end
  end
end



 models:
 class Article < ApplicationRecord

   has_one :address
   accepts_nested_attributes_for :address
 end

class Address < ApplicationRecord
end


 controller:
 class ArticlesController < ApplicationController

    def create
      @article = Article.new(params.require(:article).permit(:title, :text, :address))

     @article.save
     redirect_to @article
   end


   def show
     @article = Article.find(params[:id])
   end
end


form(new.html.erb):
    <%= form_with scope: :article, url: articles_path, local: true do |form| %>
   <p>
     <%= form.label :title %><br>
     <%= form.text_field :title %>
   </p>

<p>
  <%= form.label :text %><br>
  <%= form.text_area :text %>
</p>

<%=form.fields_for :address do |a| %>
    <div>
      <%=a.label :flat%><br>
      <%= a.text_field :flat%><br>

      <%=a.label :city%><br>
      <%= a.text_field :city%>
    </div>
<%end%>
<p>
  <%= form.submit %>
</p>

我无法将地址存储到表中。地址总是保存为 nil。如果我做错了什么,谁能指导我。我想将 json 解析到表中并将 json 存储为字符串。用我正在使用的控制器和表单更新了问题。

【问题讨论】:

  • 欢迎来到 SO,您能否添加控制器代码,您将如何使用允许的参数存储 json?
  • 用控制器更新。
  • 添加表单和提交表单后获得的参数。
  • 添加了用于表单提交的new.html.erb文件。
  • 如果您要将整个 json 存储到 address 中的 Article 模型中,那么为什么要创建另一个地址表,正如您在问题中提到的那样“将 json 解析到表并存储json 作为字符串'?

标签: ruby-on-rails migration associations


【解决方案1】:

当你想允许嵌套属性时,你需要在数组中指定嵌套对象的属性。请试试这个@article = params.require(:articles).permit(:text, :title, :address =&gt;[:flat, :city]) Rails 有一个非常好的文档请看一下​​https://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-permit

【讨论】:

    猜你喜欢
    • 2016-02-23
    • 1970-01-01
    • 2023-03-17
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多