Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple_form has_and_belongs_to_many association is not updating

I have models for Venues 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'm using simple_form to make 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 the Edit and Update 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 I update using the form, all of the attributes for the venue model update fine, but the photo_ids are not updated or stored. I'm guessing it's something simple, but I'm not sure what it is. I'm using Rails 4, btw.

like image 593
Kevin K Avatar asked May 28 '14 21:05

Kevin K


1 Answers

You need to permit photo_ids as an Array because photo_ids is passed as an Array upon form submission. Currently, photo_ids are not getting updated as you didn't permit them as an Array.

Update the venue_params as below:

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

Notice: :photo_ids => [] and NOT :photo_ids

like image 106
Kirti Thorat Avatar answered Nov 15 '22 10:11

Kirti Thorat