【发布时间】:2018-10-11 05:32:24
【问题描述】:
由于某种原因,我不能使用多态关联和嵌套形式。这是我的User、Company 和Subscription 模型:
#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 为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 %>
【问题讨论】:
-
您可以在您的视图中发布您的表单代码吗?这可能有助于进一步调查该问题。
-
添加完整的错误文本,应该有一个错误的特定行。并添加 ComaniesController#create 代码,请
-
尝试把 company_params 改成
params.require(:company).permit(:full_name, subscriptions_attributes: [:id, :name, :start_date, :stop_date]) -
在原帖中添加了表格。
标签: ruby-on-rails