Simple_form has_and_belongs_to_many关联未更新

时间:2014-05-28 21:06:56

标签: ruby-on-rails ruby-on-rails-4 associations simple-form

我有场地和照片的模型:

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

我使用simple_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>

这是我的编辑和更新方法的控制器:

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

问题在于,当我使用表单更新时,场地模型的所有属性都会更新,但不会更新或存储photo_ids。我猜它很简单,但我不确定它是什么。我使用Rails 4,顺便说一句。

1 个答案:

答案 0 :(得分:11)

您需要允许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 => []而非:photo_ids