Nested attributes with has_one polymorphic model

I am using accepts_nested_attributes_for with the has_one polymorphic model in rails 2.3.5 The following are the models and their associations:

class Address < ActiveRecord::Base
  attr_accessible :city, :address1, :address2
  belongs_to :addressable, :polymorphic => true
  validates_presence_of :address1, :address2, :city
end

class Vendor < ActiveRecord::Base
  attr_accessible :name, :address_attributes
  has_one  :address, :as => :addressable, :dependent => :destroy
  accepts_nested_attributes_for :address
end

This view:

- form_for @vendor do |f|
  = f.error_messages
  %p
    = f.label :name
    %br
    = f.text_field :name
  - f.fields_for :address_attributes do |address|
    = render "shared/address_fields", :f => address
  %p
    = f.submit "Create"

This is a partial shared / address_fields.html.haml

%p
  = f.label :city
  %br= f.text_field :city
  %span City/Town name like Dharan, Butwal, Kathmandu, ..
%p
  = f.label :address1
  %br= f.text_field :address1
  %span City Street name like Lazimpat, New Road, ..
%p
  = f.label :address2
  %br= f.text_field :address2
  %span Tole, Marg, Chowk name like Pokhrel Tole, Shanti Marg, Pako, ..

And this is the controller: VendorsController <ApplicationController class

  def new
    @vendor = Vendor.new
  end

  def create
    @vendor = Vendor.new(params[:vendor])
    if @vendor.save
      flash[:notice] = "Vendor created successfully!"
      redirect_to @vendor
    else
      render :action => 'new'
    end
  end
end

The problem is when I fill in all the fields, the record takes on both tables as expected.

But when I only filed the name and city or address1, the check works, an error message is displayed, but the value that I put in the city or address1 is not saved or not displayed inside the fields of the address form?

This is the same case with the edit action.

, . . , , SQL- .

+3
1

f.fields_for :address_attributes?

:

- f.fields_for :address do |address_fields|
  = render "shared/address_fields", :f => address_fields

, address_attributes @vendor.address.

+1

Source: https://habr.com/ru/post/1743303/


All Articles