Simple_form has_and_belongs_to_many关联未更新

Kev*_*n K 5 ruby-on-rails associations simple-form ruby-on-rails-4

我有场地和照片的模型:

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
Run Code Online (Sandbox Code Playgroud)

我正在使用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>
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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

Kir*_*rat 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
Run Code Online (Sandbox Code Playgroud)

注意: :photo_ids => []而不是:photo_ids