rails 4多张图片上传

时间:2016-10-05 02:03:51

标签: ruby-on-rails ruby ruby-on-rails-4 carrierwave multifile-uploader

目前,管理员可以创建一个仅上传一个图像的作业。我试图让管理员上传多个文件/图像供用户在作业显示页面上查看。我已经看到了实现这一目标的其他方法,但我无法找到一种方法将其实现到我的应用程序中而不会破坏它。

controller:assignments_controller.rb

class AssignmentsController < ApplicationController
  before_action :authenticate_user!
  before_filter :admin_access, only: [:new, :create, :edit, :update, :destroy]


    def index
     @assignments = Assignment.all.order("created_at DESC")
    end


   def show
     @assignment = Assignment.find(params[:id])
   end

   def new
     @assignment = Assignment.new
   end  

   def create
     @assignment = current_user.assignments.build
     @assignment.name = params[:assignment][:name]
     @assignment.description = params[:assignment][:description]
     @assignment.picture = params[:assignment][:picture]


     if @assignment.save
       flash[:notice] = "Assignment was saved successfully."
       redirect_to @assignment
     else
       flash.now[:alert] = "Error creating assignment. Please make sure there is a name and description."
       render :new
     end
   end

     def edit
     @assignment = Assignment.find(params[:id])
     end

      def update
     @assignment = Assignment.find(params[:id])

     @assignment.name = params[:assignment][:name]
     @assignment.description = params[:assignment][:description]
     @assignment.picture = params[:assignment][:picture]

     if @assignment.save
        flash[:notice] = "Assignment was updated successfully."
       redirect_to @assignment
     else
       flash.now[:alert] = "Error saving assignment. Please try again."
       render :edit
     end
      end

   def destroy
     @assignment = Assignment.find(params[:id])

     if @assignment.destroy
       flash[:notice] = "\"#{@assignment.name}\" was deleted successfully."
       redirect_to action: :index
     else
       flash.now[:alert] = "There was an error deleting the assignment."
       render :show
     end
   end

     private 

     def assignment_params
         params.require(:assignment).permit(:name, :description, :picture)
     end
end

型号:assignment.rb

class Assignment < ActiveRecord::Base
        has_many :submits, dependent: :destroy
        belongs_to :user
        validates :name, length: { minimum: 1, maximum:120 }
        validates :description, length: { minimum: 1 }
        mount_uploader :picture, AssignmentpicUploader
end

提交模型/控制器将学生作业提交给管理员

控制器:提交

class SubmitsController < ApplicationController
  before_action :authenticate_user!
  load_and_authorize_resource param_method: :my_sanitizer
  load_and_authorize_resource :through => :current_user


  def index
      @submits = Submit.all.order("created_at DESC")
  end

   def show
     @submit = Submit.find(params[:id])
   end

   def new
      @submit = current_user.submits.build
   end

   def create
      @submit = current_user.submits.build(submit_params)

      if @submit.save
         redirect_to submits_path, notice: "The assignment #{@submit.name} has been uploaded."
      else
         render "new"
      end

   end

   def destroy
      @submit = Submit.find(params[:id])
      @submit.destroy
      redirect_to submits_path, notice:  "The assignment #{@submit.name} has been deleted."
   end

   private
      def submit_params
      params.require(:submit).permit(:name, :attachment)
      end

end

型号:submit.rb

class Submit < ActiveRecord::Base
    belongs_to :assignment
    belongs_to :user
    validates :name, presence: true # Make sure the owner's name is present.
    mount_uploader :attachment, AttachmentUploader # Tells rails to use this uploader for this model.
end

上传者:assignmentpic_uploader.rb

# encoding: utf-8

class AssignmentpicUploader < CarrierWave::Uploader::Base


  include CarrierWave::MiniMagick


   storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  # Create different versions of your uploaded files:
  version :large do
     process :resize_to_fit => [500, 700]
  end

  # Add a white list of extensions which are allowed to be uploaded.
   def extension_white_list
     %w(jpg jpeg gif png)
   end

end

视图/分配:

edit.html.erb

<h1>Edit Assignment</h1>

 <div class="row">
   <div class="col-md-4">
     <p>Guidelines for topics:</p>
     <ul>
       <li>Make sure the topic is appropriate.</li>
       <li>Never insult dogs.</li>
       <li>Smile when you type.</li>
     </ul>
   </div>
   <div class="col-md-8">
     <%= form_for @assignment do |f| %>
       <div class="form-group">
         <%= f.label :name %>
         <%= f.text_field :name, class: 'form-control', placeholder: "Enter assignment name" %>
       </div>
       <div class="form-group">
         <%= f.label :description %>
         <%= f.text_area :description, rows: 8, class: 'form-control', placeholder: "Enter assignment description" %>
       </div>
       <div class="form-group">
      <%= f.label :picture %>
      <%= f.file_field :picture %>
      </div>
      <br />
       <%= f.submit "Save", class: 'button' %>
     <% end %>
   </div>
 </div>

index.html.erb

  <div class="col-lg-12 text-center">
<h1>Assignments 

    <% if current_user.admin %>
     <%= link_to "New Assignment", new_assignment_path, class: 'btn btn-success' %>
     <% end %>
        <hr>
</h1>
  </div>

 <div class="row">
   <div class="col-md-10">
 <!-- #7 -->
     <% @assignments.each do |assignment| %>
       <div class="media">
         <div class="media-body">
           <h3 class="media-heading">
 <!-- #8 <--> 
             <%= link_to assignment.name, assignment %>
           </h3>
                                   <!-- Date/Time -->
        <p><span class="glyphicon glyphicon-time"></span> 
        <%= time_ago_in_words(assignment.created_at) %> ago
        </p>
           <small>
             <%= assignment.description %>
           </small>
         </div>
       </div>
       <hr>
     <% end %>
   </div>
   <br>

   </div>

new.html.erb

<h1>New Assignment</h1>

 <div class="row">
   <div class="col-md-4">
     <p>Guidelines for topics:</p>
     <ul>
       <li>Make sure the topic is appropriate.</li>
       <li>Never insult dogs.</li>
       <li>Smile when you type.</li>
     </ul>
   </div>
   <div class="col-md-8">
     <%= form_for @assignment do |f| %>
       <div class="form-group">
         <%= f.label :name %>
         <%= f.text_field :name, class: 'form-control', placeholder: "Enter assignment name" %>
       </div>
       <div class="form-group">
         <%= f.label :description %>
         <%= f.text_area :description, rows: 8, class: 'form-control', placeholder: "Enter assignment description" %>
       </div>
       <div class="form-group">
      <%= f.label :picture %>
      <%= f.file_field :picture %>
      </div>
      <br />
       <%= f.submit "Save", class: 'button' %>
     <% end %>
   </div>
 </div>

show.html.erb

 <h1><%= @assignment.name %>

 <% if current_user.admin %>
    <%= link_to "Edit Assignment", edit_assignment_path, class: 'btn btn-success btn-sm round' %>
    <%= link_to "Delete Assignment", @assignment, method: :delete, class: 'btn btn-danger btn-sm round ', data: { confirm: 'Are you sure you want to delete this assignment?' } %>
<% end %>
 </h1>
 <div class="row">
   <div class="col-md-8">
     <p class="lead"><%= @assignment.description %></p>
 <!-- #10 -->
     <% @assignment.submits.each do |submit| %>
       <div class="media">
         <div class="media-body">
           <h4 class="media-heading">
             <%= link_to submit.name, submit %>
           </h4>
         </div>
       </div>
     <% end %>
   </div>


   <div id="img">
    <%= image_tag @assignment.picture.url(:large) %>
  </div>

  </br>
   <div class="col-md-4">
     <%= link_to "Submit Assignment", new_submit_path(@assignment), class: 'button' %>
   </div>
 </div>

视图/提交:

index.html.erb

<div class="col-lg-12 text-center">
   <h1>Student Work</h1>
   <hr>
</div>

 <% if current_user.admin %>
<small>Hold "CTRL" + "F" to search for assignment or student name.</small>
 <% end %>
<br />
<br />

<table class = "table table-bordered table-striped">
   <thead>
      <tr>
         <th>Name</th>
         <th>View Assignments</th>
         <th>Delete</th>
      </tr>
   </thead>

   <tbody>
      <% @submits.each do |submit| %>

         <tr>
            <% if can? :destroy, submit %>
            <td><%= submit.name %></td>
            <td><%= link_to "View Assignment", submit.attachment_url %></td>
            <td><%= button_to "Delete",  submit, method: :delete, class: "button", data: { confirm: "Are you sure that you wish to delete #{submit.name}?" } %></td>
            <% end %>
         </tr>

      <% end %>
   </tbody>

</table>

new.html.erb

<div class="text-center">
<h1>Submit Assignment</h1>
</div>
<hr>

<% if !@submit.errors.empty? %>
   <div class = "alert alert-error">

      <ul>
         <% @submit.errors.full_messages.each do |msg| %>
            <li><%= msg %></li>
         <% end %>
      </ul>

   </div>
<% end %>

<div class = "well">
   <%= form_for @submit, html: { multipart: true } do |f| %>
      <%= f.label :name %>
      <%= f.text_field :name %>
      <br />
      <%= f.label :attachment %>
      <%= f.file_field :attachment %>
      <br />
      <%= f.submit "Save", class: "button" %>
   <% end %>
   </div>

   <p>Please include "ASSIGNMENT NAME - YOUR NAME" in the field above</p>

   <br />
   <p> Example:</p>

   <small> assignment 1 - Bob Smith</small>

schema.rb

# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema.define(version: 20160930021506) do

  create_table "articles", force: :cascade do |t|
    t.string   "title"
    t.text     "body"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer  "user_id"
  end

  create_table "assignments", force: :cascade do |t|
    t.string   "name"
    t.text     "description"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.integer  "user_id"
    t.string   "picture"
  end

  add_index "assignments", ["user_id"], name: "index_assignments_on_user_id"

  create_table "clients", force: :cascade do |t|
    t.string   "name"
    t.string   "email"
    t.text     "message"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "phone"
  end

  create_table "comments", force: :cascade do |t|
    t.text     "body"
    t.integer  "user_id"
    t.integer  "article_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_index "comments", ["article_id"], name: "index_comments_on_article_id"
  add_index "comments", ["user_id"], name: "index_comments_on_user_id"

  create_table "contacts", force: :cascade do |t|
    t.string   "name"
    t.string   "email"
    t.text     "message"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "submits", force: :cascade do |t|
    t.string   "name"
    t.string   "attachment"
    t.integer  "assignment_id"
    t.integer  "user_id"
    t.datetime "created_at",    null: false
    t.datetime "updated_at",    null: false
  end

  create_table "users", force: :cascade do |t|
    t.string   "username",               default: "",    null: false
    t.string   "email",                  default: "",    null: false
    t.string   "encrypted_password",     default: "",    null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,     null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.string   "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.string   "unconfirmed_email"
    t.datetime "created_at",                             null: false
    t.datetime "updated_at",                             null: false
    t.boolean  "admin",                  default: false
    t.string   "firstname"
    t.string   "lastname"
  end

  add_index "users", ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

end

对不起,如果信息太多或太少。 也提前感谢你们这里所有精彩的人都愿意伸出援助之手。

0 个答案:

没有答案