我是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>
我无法将adrress存储到表中。地址始终保存为零。如果我做错了,任何人都可以指导我。我想将json解析为表并将json存储为字符串。使用我正在使用的控制器和表单更新了问题。
如果要允许嵌套属性,则可以在数组中指定嵌套对象的属性。请试试这个@article = params.require(:articles).permit(:text, :title, :address =>[:flat, :city])
Rails有一个非常好的文档请看看https://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-permit