【发布时间】:2023-03-16 06:08:01
【问题描述】:
我无法保存我的签到记录,因为相关的租赁没有保存。
我有三个具有关联的模型:
class Property < ApplicationRecord
has_many :tenancies
end
class Tenancy < ApplicationRecord
belongs_to :property
has_many :check_ins
end
class CheckIn < ApplicationRecord
belongs_to :tenancy
accepts_nested_attributes_for :tenancy
end
我希望 CheckIn 新操作创建 CheckIn 和关联的租户:
def new
@check_in = CheckIn.new
@check_in.build_tenancy.property_id = params[:property_id]
end
我必须包含 property_id 部分,否则租户将无法保存。
check_ins/new.html.erb 中的表单:
<%= form_for @check_in, url: property_check_ins_path do |f| %>
<%= f.label :date_time %>
<%= f.datetime_select :date_time, {minute_step: 15} %>
<%= f.label :tenancy %>
<%= f.fields_for :tenancy do |i| %>
<%= i.date_select :start_date %>
<% end %>
<%= f.submit "Create Check In" %>
<% end %>
我在 CheckInsController 的强参数中添加了租户属性:
def check_in_params
params.require(:check_in).permit(:tenancy_id, :date_time, tenancy_attributes: [:start_date])
end
值得注意的是 check_ins 路由嵌套在属性中:
resources :properties do
resources :check_ins, only: [:new, :create]
end
所以问题是,当我在 CheckInsController 中执行创建操作时,我建立的租户已经消失了。我不确定应该如何以及何时保存每条记录,而且我试图实现的目标的轻微复杂性使得很难找到相关帮助,所以有什么想法吗?
我正在使用 Rails 5。
【问题讨论】:
-
你在strong_params中添加了
tenancy_attributes -
我有,我在原始问题中添加了这个,谢谢
-
啊,我刚刚意识到我在允许的参数中没有 :tenancy_id .. 但是我把它放进去,它仍然没有保存
标签: ruby-on-rails activerecord associations nested-attributes