【发布时间】: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