Вопрос

Интересный фрагмент кода, с которым я не могу работать.У меня есть следующие модели/отношения (исключая ненужный код)

class Service < ActiveRecord::Base
  belongs_to :service_category, :foreign_key => "cats_uid_fk"
  belongs_to :service_type, :foreign_key => "types_uid_fk"
  has_and_belongs_to_many :service_subtypes, :join_table => "services_to_service_subs"
  belongs_to :service_request, :foreign_key => "audits_uid_fk"

  accepts_nested_attributes_for :service_subtypes
end

class ServiceSubtype < ActiveRecord::Base
  belongs_to :service_types, :foreign_key => "types_uid_fk"
  has_and_belongs_to_many :services, :join_table => "services_to_service_subs"
end

Форма, отображающая всю эту информацию:

<% form_for(@request, :url => { :action => :create }) do |form| %>
 <table>   

...other data...

 <% form.fields_for :services do |fields| %>
  <%= fields.hidden_field :cats_uid_fk %>
  <%= fields.hidden_field :types_uid_fk %>
  <% fields.fields_for :service_subtypes do |subtype| %>
   <%= subtype.hidden_field :id %>
  <% end %> 
 <% end %>   

 <p>
   <%= form.submit "Create", :class=>"hargray" %>
 </p>         
<% end %> 

И контроллер для обработки отправки:

def create
 logger.debug params[:service_request].inspect

 @request = ServiceRequest.new(params[:service_request])
 if session[:cus_id]
  @request.customer = Customer.find session[:cus_id]
 end

 begin      
  @request.save!
  flash[:notice] = "Information submitted successfully. You will be contacted by a customer service representative regarding the services you selected."
  redirect_to :controller => "customer", :action => "index"
 rescue Exception => exc
  flash[:notice] = "#{ format_validations(@request) } - #{exc.message}"
  render :action => "new"
 end

end

HTML выглядит чистым:

<input id="service_request_services_attributes_0_cats_uid_fk" name="service_request[services_attributes][0][cats_uid_fk]" type="hidden" value="1" />
  <input id="service_request_services_attributes_0_types_uid_fk" name="service_request[services_attributes][0][types_uid_fk]" type="hidden" value="1" />
  <input id="service_request_services_attributes_0_service_subtypes_attributes_0_id" name="service_request[services_attributes][0][service_subtypes_attributes][0][id]" type="hidden" value="2" />
   <input id="service_request_services_attributes_0_service_subtypes_attributes_0_id" name="service_request[services_attributes][0][service_subtypes_attributes][0][id]" type="hidden" value="2" />
  <input id="service_request_services_attributes_0_service_subtypes_attributes_1_id" name="service_request[services_attributes][0][service_subtypes_attributes][1][id]" type="hidden" value="4" />
   <input id="service_request_services_attributes_0_service_subtypes_attributes_1_id" name="service_request[services_attributes][0][service_subtypes_attributes][1][id]" type="hidden" value="4" />

Отправленные параметры выглядят следующим образом:

{
...other data...
 "services_attributes"=> {
  "0"=> {
   "types_uid_fk"=>"1", 
   "service_subtypes_attributes"=> {
    "0"=>{"id"=>"1"}, 
    "1"=>{"id"=>"2"}, 
    "2"=>{"id"=>"3"}
   }, 
   "cats_uid_fk"=>"1"
  }
 }
}

Я получаю сообщение об ошибке «неопределенный метод «service_subtype» для #», и единственная необновленная таблица — это таблица соединений между моделями HABTM.Есть идеи, как решить эту проблему или что происходит за кулисами?Я не уверен, что понимаю «волшебство», происходящее за этой процедурой, и вижу, как она работает.Кажется, большинство говорят, что HABTM не работает с вложенными атрибутами.Кажется, это так.Обходные пути?

Это было полезно?

Решение 2

Нашел ту ошибку, была в моих почтовиках.В любом случае, field_for :subtypes по-прежнему не генерировал правильные параметры для магии вложенных атрибутов, чтобы понять, что я пытался сделать.

В итоге я получаю следующее:

новый.erb

<% form.fields_for :services do |fields| %>
    <%= fields.hidden_field :wsi_web_serv_cats_uid_fk %>
    <%= fields.hidden_field :wsi_web_serv_types_uid_fk %>
    <%= fields.hidden_field :service_subs_hash %>
<% end %>

сервис.рб

def service_subs_hash
    self.service_subtype_ids.join(", ")
end

def service_subs_hash=(ids)
    self.service_subtype_ids = ids.split(",")
end

Я чувствую это как-то хакерски, и я не уверен, что полностью удовлетворен этим ответом, но в моем скрытом поле помещается список, разделенный запятыми, который я могу снова проанализировать на service_subtype_ids при отправке.

Если кто-нибудь знает, как это сделать без этого дополнительного виртуального параметра, я бы хотел знать.

Спасибо за помощь.

Другие советы

Предполагая, что это не ошибка копирования и вставки в модели службы, это может быть источником вашей проблемы.

 accepts_nested_attributes_for :services_subtypes

Должно быть

 accepts_nested_attributes_for :service_subtypes

Первыми аргументами Accepts_nested_attributes_for должна быть ассоциация, определенная оператором has_many, has_and_belongs_to_many или own_to.

Вторая незначительная проблема, связанная с двойной генерацией скрытого поля, связана с его вставкой в ​​раздел поля_for.field_for автоматически включает скрытое поле для идентификатора.Делаем безопасным удаление скрытой строки поля из следующего блока.

<% fields.fields_for :service_subtypes do |subtype| %>
  <%= subtype.hidden_field :id %>
<% end %> 
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top