2016-02-22 100 views
0

[这可能是一个简单的问题,但我不能找到一个解决方案]与simple_form和回形针嵌套模型

我试图用新数据更新现有的记录和一些图像(S)添加到该记录(通过回形针),但是,我的代码根本不显示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 

这里的形式,在这里你可以看到回形针场缺少的打印屏幕:

preview


但是,当我改变f.simple_fields_for :hotel_images到,例如,f.simple_fields_for :foobars,回形针字段显示为:

example2


注意:在namelocation属性更新就好了。

回答

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 

试试这个代码

+0

的回形针场仍然不显示。 – Vucko

+0

粘贴您的编辑动作代码 –

+0

尝试更新代码 –