【问题标题】:Nested models with simple_form and paperclip带有 simple_form 和回形针的嵌套模型
【发布时间】:2016-02-22 09:19:55
【问题描述】:

[这可能是一个简单的问题,但我找不到解决方案]

我正在尝试使用新数据更新现有记录并向该记录添加一些图像(通过回形针),但是,我的代码根本没有显示 paperclip 字段。

I've followed this example 也尝试了this solutions,但没有任何效果。

我有两个,型号 HotelHotelImage

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

这是表单的打印屏幕,您可以在其中看到回形针字段丢失:


但是,当我将f.simple_fields_for :hotel_images 更改为f.simple_fields_for :foobars 时,会显示回形针字段:


注意namelocation 属性更新正常。

【问题讨论】:

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


    【解决方案1】:
    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
    

    试试这个代码

    【讨论】:

    • 回形针字段仍然不显示。
    • 是的,就是这样。我忘了更新编辑方法 :stupid_me: 。谢谢:)
    猜你喜欢
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多