我有模型工作和模型用户,两者都可以选择合同类型(这就是我使用多态的原因)。
我为每个合约创建了一个模型合约,我也创建了一个attach_contract模型。
工作模式
class Job < ApplicationRecord
has_many :contracts, through: :attached_contracts
has_many :attached_contracts, as: :contractable, dependent: :destroy
accepts_nested_attributes_for :attached_contracts, reject_if: :all_blank, allow_destroy: true
end
AttachedContract模型
class AttachedContract < ApplicationRecord
belongs_to :contract
belongs_to :contractable, polymorphic: true
validates :contract, uniqueness: { scope: [:contractable_type,:contractable_id] }
end
合同模式
class Contract < ApplicationRecord
validates :name, presence: true, allow_blank: false
has_many :attached_contracts
end
Jobs_controller
def new
@job = Job.new
@job.attached_contracts.build
end
def create
@job = current_company.jobs.build(set_params)
if @job.save
redirect_to job_path(@job)
end
else
render :new
end
end
def set_params
params.require(:job).permit(:title, :description, :address, attached_contracts_attributes: [:id, :contract_id, :_destroy]
end
在我看来:
<%= simple_form_for([:company, @job]) do |f| %>
<div class="nested-fields">
<%= f.association :contracts, as: :check_boxes %>
</div>
<% end %>
当我提交表单时,我的模型AttachedContract仍为空,数据丢失。
我尝试在@job = current_company.jobs.build(set_params)之后在我的控制器中添加“加注” 如果我打电话给@ job.attached_contracts,我有一个空数组 我不明白beause在“请求参数”(rails debug console)中我有值:“contract_ids”=&gt; [“”,“1”,“3”]
有什么想法吗?可能是多态植入的问题?
答案 0 :(得分:0)
最后,我通过&#34; contract_ids更改了请求的参数:[]&#34;这完美无瑕!