轨道、多态关联和表单助手



由于某种原因,我无法使用多态关联和嵌套形式。以下是我的UserCompanySubscription模型:

#app/models/user.rb
class User < ApplicationRecord
has_many subscriptions, dependent: :destroy, as: :imageable
end

.

#app/models/company.rb
class Company < ApplicationRecord
has_many :subscriptions, dependent: :destroy, as: :imageable
end

.

#app/models/subscription.rb
class Subscription < ApplicationRecord
belongs_to :imageable, polymorphic: true
end

这是我的Company控制器中的内容:

def company_params
params.require(:company).permit(:full_name, :subscriptions_attributes => {})
end

当我尝试在选择嵌套订阅的情况下提交表单时,这是我收到的错误:

Processing by ComaniesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"daP0snbHyLNm4KlzoO3YnkBrU/pD6ksUuOFp4icB74h0Uf929UT+4TAMxbuTBCwu5w+HWH3zD0gP3TwXcAmrHQ==", "company"=>{"full_name"=>"Test", "subscriptions_attributes"=>{"0"=>{"name"=>"", "start_date"=>"", "stop_date"=>""}}}}
User Load (0.5ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1
(0.4ms)  BEGIN
Completed 500 Internal Server Error in 89ms (ActiveRecord: 6.4ms)

但是如果我转到 Rails 控制台,我可以成功键入Company.subscriptions.create(name: "Random")

我做错了什么?在我实现多态关联之前,它工作正常,但现在我无法弄清楚这一点。

编辑

经过进一步调查,似乎失败的原因是因为公司的订阅不包含imageable_id

在我的Company控制器中,我有以下内容:

# GET /companies/new
def new
@company = Company.new
@company.subscriptions.build
end

当我检查@company.subscription时,我可以看到imageable_type已经预设为"公司",但imageable_id为零,从未填写过。

这到底应该在哪里填写?

编辑

这是表格:

<%= form_with(model: @company, local: true) do |form| %>
...
<tbody>
<%= form.fields_for :subscriptions do |subscription| %>
<tr>
<td><%= subscription.text_field :name, :subscription_name, class: "form-control" %></td>
<td><%= subscription.date_field :start_date, as: :date, value: subscription.object.try(:strftime,"%m/%d/%Y"), class: 'form-control' %></td>
<td><%= subscription.date_field :stop_date, as: :date, value: subscription.object.try(:strftime,"%m/%d/%Y"), class: 'form-control' %></td>
<td><%= link_to "<i class='fas fa-trash'></i>".html_safe, '#', class: "btn btn-xs btn-danger delete_row" %></td>
</tr>
<% end %>
</tbody>
...
<% end %>

哇。经过无数个小时后,我只需要使关联成为可选:

belongs_to :imageable, polymorphic: true, optional: true

最新更新