简体   繁体   中英

Nested models with simple_form and paperclip

[This maybe a simple issue, but I just can't find a solution]

I'm trying to update an existing record with new data and add some image(s) to that record (via paperclip), however, my code doesn't show the paperclip field at all.

I've followed this example and also tried with this solutions , but nothing works.

I have two, models Hotel and HotelImage .

hotel.rb

class Hotel < ActiveRecord::Base
  extend FriendlyId
  friendly_id :slug_candidates, use: :slugged

  validates :name, presence: true
  validates :location, presence: true

  has_many :hotel_images
  accepts_nested_attributes_for :hotel_images

  def slug_candidates
    [
      [:name, :location],
    ]
  end
end

hotel_image.rb

class HotelImage < ActiveRecord::Base
  belongs_to :hotel

  #rails generate paperclip hotel_image image

  has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
  validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
end

edit.html.erb

<%= simple_form_for @hotel, :url => admin_hotel_path, method: :put, html: { multipart: true } do |f| %>
  <%= f.error_notification %>
  <%= f.input :name %>
  <%= f.input :location %>

  <%= f.simple_fields_for :hotel_images do |ff| %>
    <%= ff.input :image, as: :file %>
  <% end %>

  <%= f.button :submit %>
<% end %>

hotels_controller.rb

#other code

def update
  @hotel = Hotel.friendly.find(params[:slug])

  if @hotel.update(hotel_params)
    redirect_to admin_hotels_path, notice: 'Hotel was successfully updated.'
  else
    render :edit
  end
 end

private

def hotel_params
  params.require(:hotel).permit(:name, :location, :admin_id, hotel_images_attributes: [:hotel_id, :image])
end

Here's the print screen of the form, where you can see that the paperclip field is missing:

预习


However, when I change f.simple_fields_for :hotel_images to, for example, f.simple_fields_for :foobars , the paperclip field is shown:

例子2


Note : the name and location attributes update just fine.

def update
  @hotel = Hotel.friendly.find(params[:slug])
  if @hotel.update(hotel_params)
    redirect_to admin_hotels_path, notice: 'Hotel was successfully updated.'
  else
    render :edit
  end
end

def edit
  @hotel_images = @hotel.hotel_images.present? ? @hotel.hotel_images : @hotel.hotel_images.build
end

Try this code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM