Rails,多态关联和表单帮助器

时间:2018-10-11 05:32:25

标签: ruby-on-rails

由于某种原因,我不能使用多态关联和嵌套形式。这是我的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已经预设为“ Company”,但是imageable_id为nil并且从未填写。

应该在哪里填写?

编辑

这是表格:

<%= 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 %>

1 个答案:

答案 0 :(得分:0)

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

belongs_to :imageable, polymorphic: true, optional: true