kid_drew
kid_drew

Reputation: 3995

Rails scoped association w/ nested form

I have the following classes:

class Business < AR::Base
  has_many :locations
  has_many :owned_locations, -> { owned }, class_name: 'Location'
  has_many :good_locations, -> { good }, class_name: 'Location'
  has_many :bad_locations, -> { bad }, class_name: 'Location'
  accepts_nested_attributes_for :locations, allow_destroy: true
  accepts_nested_attributes_for :owned_locations, allow_destroy: true
  accepts_nested_attributes_for :good_locations, allow_destroy: true
  accepts_nested_attributes_for :bad_locations, allow_destroy: true
end

class Location < AR::Base
  belongs_to :business
  scope :owned, -> { where(type: 'owned') }
  scope :good, -> { where(type: 'good') }
  scope :bad, -> { where(type: 'bad') }
end

Basically I'm trying to set up an association where locations can be assigned to multiple buckets (types) but all be stored in the same table. I'm running into an issue with a nested form:

= simple_form_for @business do |f|
  = f.fields_for :owned_locations, @business.owned_locations do |lf|
    # location fields

My controller has the appropriate permitted params:

params.permit(
  :business => [
    :name,
    :owned_locations_attributes => [
      # locations_attributes
    ]
  ]
)

I'm not getting any unpermitted params errors, so I'm confident I have that all set up correctly. But the locations are not getting assigned to the business. These are the errors:

{
  :"owned_locations.business"=>["can't be blank"], 
  :"good_locations.business"=>["can't be blank"], 
  :"bad_locations.business"=>["can't be blank"]
}

I don't know enough about the inner-workings of the Rails API to debug this. Any idea what I'm doing wrong?

Upvotes: 1

Views: 44

Answers (1)

neo
neo

Reputation: 4116

You need to use simple_fields_for when you're creating a nested form with simple_form.

= simple_form_for @business do |f|
  = f.simple_fields_for :owned_locations, @business.owned_locations do |lf|
        # location fields

Upvotes: 1

Related Questions