Simple_form has_and_belongs_to_many association does not update

I have models for places and photos:

class Venue < ActiveRecord::Base
  has_and_belongs_to_many :photos

  validates :name, presence: true
  validates :permalink, presence: true, uniqueness: true

  def to_param
    permalink
  end
end

class Photo < ActiveRecord::Base
  mount_uploader :image, PhotoUploader

  has_and_belongs_to_many :venues
end

I use simple_form to create the following form:

<div class="content-box">
  <%= simple_form_for [:admin, @venue] do |f| %>
    <%= f.input :name %>
    <%= f.input :permalink %>
    <%= f.input :description, input_html: { cols: 100, rows: 6 }%>
    <%= f.input :address %>
    <%= f.input :city %>
    <%= f.input :phone %>
    <%= f.association :photos %> 
    <%= f.button :submit, class: 'small radius' %>
  <% end %>
</div>

And here is my controller for editing and updating methods:

class Admin::VenuesController < ApplicationController

  def edit
    @venue = Venue.find_by_permalink!(params[:id])
    @photos = @venue.photos.all
  end

  def update
    @venue = Venue.find_by_permalink!(params[:id])
    if @venue.update_attributes(venue_params)
      redirect_to edit_admin_venue_path(@venue), notice: 'Venue was successfully updated.'
    else
      render action: "edit"
    end
  end

  private

  def venue_params
    params.require(:venue).permit(:name, :permalink, :description, :address, :city, :phone, :photo_ids)
  end
end

The problem is that when updating using the form, all the attributes for updating the location model are fine, but the photo data is not updated and not updated. I suppose this is something simple, but I'm not sure what it is. I am using Rails 4, by the way.

+4
source share
1 answer

photo_ids Array, photo_ids Array . photo_ids , Array.

venue_params, :

def venue_params
  params.require(:venue).permit(:name, :permalink, :description, :address, :city, :phone, :photo_ids => [])
end

: :photo_ids => [] NOT :photo_ids

+9

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


All Articles