使用Ruby on Rails向博客文章中添加多个图像或不添加图像

时间:2019-06-23 17:20:38

标签: ruby-on-rails image repl.it

我正在为K-pop粉丝建立一个网站,以发布有关K-pop的任何信息。我目前正在遵循建立网站的教程,但是我希望用户可以选择不上传照片或上传一张或多张照片。我该如何实现?

(这是我关注的教程https://www.youtube.com/watch?v=BI_VnnOLSKY

我尝试搜索“添加多张照片或不使用滑轨添加照片”,但是它们仅显示“如何添加照片以张贴”或类似内容。

我正在使用repl.it来制作网站。

1 个答案:

答案 0 :(得分:0)

您想要的功能是在提交中添加多个元素以实现此目的,在Ruby on Rails中,您可以使用accepts_nested_attributes_for,这是在提交中包括嵌套属性的标准功能:

#app/models/post.rb (or blog_post whatever your model name)
class Post < ActiveRecord::Base
   has_many :images # association with image model
   accepts_nested_attributes_for :images, reject_if: :all_blank, allow_destroy: true
end

在routes.rb文件中:-

#config/routes.rb
resources :posts

在控制器文件中:-

#app/controllers/posts_controller.rb
class PostsController < ApplicationController

   def new
     @post = Post.new
     @post.images.build
   end

  .
  .
  .
end

以下代码应为您提供一个@post表单,其中包含嵌入的图像。 要添加“额外”字段,您最好查看cocoon gem或以下Railscast:Nested Forms part 1

我在这里使用"nested_form" gem:-

#app/views/posts/new.html.erb
<%= nested_form_for @post do |f| %>
  <%= f.text_field :x %>
  <%= f.text_field :y %>
  .
  .
  .

  <%= f.fields_for :images do |i| %>
     <% if i.object.new_record? %>
       <%= i.file_field :attachment %>
     <% else %>
       <%= image_tag i.object.attachment.url %>
     <% end %>
     <%= i.link_to_remove "Remove image" %>
  <% end %>
  <p><%= f.link_to_add "Add image", :images%></p>


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

我希望以上代码将帮助您实现功能:)