我是红宝石的新手,我正尝试在表中存储嵌套的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存储到表中。地址始终保存为nil。如果我做错了谁能指导我。我想将json解析到表中并将json存储为字符串。更新了我正在使用的控制器和表格的问题。
答案 0 :(得分:0)
要允许嵌套属性时,请在数组中指定嵌套对象的属性。请尝试这个@article = params.require(:articles).permit(:text, :title, :address =>[:flat, :city])
Rails有一个很好的文档,请看看https://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-permit