Ruby on Rails 从一种形式保存在两个表中 [英] Ruby on Rails Saving in two tables from one form
问题描述
我有两个模型 Hotel 和 Address.关系是:
I have two models Hotel and Address. Relationships are:
class Hotel
belongs_to :user
has_one :address
accepts_nested_attributes_for :address
和
class Address
belongs_to :hotel
我需要从一个表单中保存在 hotels 表和 addresses 表中.
And I need to save in hotels table and in addresses table from one form.
输入表单很简单:
<%= form_for(@hotel) do |f| %>
<%= f.text_field :title %>
......other hotel fields......
<%= f.fields_for :address do |o| %>
<%= o.text_field :country %>
......other address fields......
<% end %>
<% end %>
酒店控制器:
class HotelsController < ApplicationController
def new
@hotel = Hotel.new
end
def create
@hotel = current_user.hotels.build(hotel_params)
address = @hotel.address.build
if @hotel.save
flash[:success] = "Hotel created!"
redirect_to @hotel
else
render 'new'
end
end
但是这段代码不起作用.
But this code doesn't work.
加 1Hotel_params:
ADD 1 Hotel_params:
private
def hotel_params
params.require(:hotel).permit(:title, :stars, :room, :price)
end
添加 2
主要问题是我不知道如何正确渲染表单.这个 ^^^ 表格甚至不包括地址字段(国家、城市等).但是如果在一行
The main problem is I don't know how to render form properly. This ^^^ form doesn't even include adress fields (country, city etc.). But if in the line
<%= f.fields_for :address do |o| %>
我将:address 更改为:hotel,我在表单中获得了地址字段,但当然在这种情况下,:address 表中没有保存任何内容.我不明白从 1 个表单保存在 2 个表中的原理,非常抱歉,我是 Rails 新手...
I change :address to :hotel, I get address fields in the form, but of course nothing saves in :address table in this case. I don't understand the principle of saving in 2 tables from 1 form, I'm VERY sorry, I'm new to Rails...
推荐答案
您正在使用错误的方法
将您的孩子附加到父级.而且它是has_one 关系
,所以你应该使用 build_model
而不是 model.build
strong>.你的new
和create
方法应该是这样的
You are using wrong method
for appending your child with the parent.And also it is has_one relation
,so you should use build_model
not model.build
.Your new
and create
methods should be like this
class HotelsController < ApplicationController
def new
@hotel = Hotel.new
@hotel.build_address #here
end
def create
@hotel = current_user.hotels.build(hotel_params)
if @hotel.save
flash[:success] = "Hotel created!"
redirect_to @hotel
else
render 'new'
end
end
更新
您的 hotel_params
方法应该如下所示
Your hotel_params
method should look like this
def hotel_params
params.require(:hotel).permit(:title, :stars, :room, :price,address_attributes: [:country,:state,:city,:street])
end
这篇关于Ruby on Rails 从一种形式保存在两个表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!