通过has_one多态关联--Rails 4通过CarrierWave上传图像

时间:2016-06-05 00:20:34

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

我已经创建了一个图像模型,可以通过多态关联将所有上传的图像(通过CarrierWave)存储到我的应用中。

个人资料可以通过此关联拥有一张图片。

目前有哪些工作:

  • CarrierWave已成功将图片上传至public/uploads/temp
  • Rails控制台没有错误,但发生了(无关的?)回滚

什么不起作用:

  • 在提交
  • 上的图像表中没有保存任何内容

任何指示赞赏!

profile.rb

class Profile < ActiveRecord::Base

  belongs_to :user
  has_one :image, as: :imageable, dependent: :destroy
  has_and_belongs_to_many :genres, -> { order "name asc" }
  has_and_belongs_to_many :talents, -> { order "name asc" }
  has_and_belongs_to_many :influences, -> { order "name asc" }

  accepts_nested_attributes_for :image
  accepts_nested_attributes_for :influences
  accepts_nested_attributes_for :talents
  accepts_nested_attributes_for :genres

end

image.rb

class Image < ActiveRecord::Base

  belongs_to :imageable, polymorphic: true
  mount_uploader :image, ImageUploader
  validates_presence_of :image
  validates_integrity_of :image

end

image_uploader.rb

class ImageUploader < 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 :thumb do
    process :resize_to_fill => [100, 100]
  end
  version :grid do
    process :resize_to_fill => [600, 400]
  end
  version :large do
    process :resize_to_fit => [1000, 1000]
  end
  version :mega do
    process :resize_to_fit => [2000, 2000]
  end

  def extension_white_list
    %w(jpg jpeg gif png)
  end

end

简档/ show.html.erb

<%= form_for @profile, html: { multipart: true } do |f| %>
  <%= f.fields_for :image_attributes do |image_f| %>
    <%= image_f.label :image %><br>
    <%= image_f.file_field :image %>
    <%= image_f.hidden_field :imageable_id, value: @profile.id %>
    <%= image_f.hidden_field :imageable_type, value: "image" %>
  <% end %>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

schema.rb

create_table "profiles", force: :cascade do |t|
  t.string   "name"
  t.string   "website"
  t.string   "details"
  t.string   "soundcloud"
  t.string   "bandcamp"
  t.string   "facebook"
  t.string   "instagram"
  t.string   "twitter"
  t.datetime "created_at",   null: false
  t.datetime "updated_at",   null: false
  t.string   "slug"
  t.integer  "availability"
  t.string   "spotify"
  t.string   "applemusic"
  t.integer  "user_id"
  t.integer  "visible"
end

create_table "images", force: :cascade do |t|
  t.string   "image"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.integer  "imageable_id"
  t.string   "imageable_type"
end

profiles_controller.rb

class ProfilesController < ApplicationController

  before_action :authenticate_user!, :except => [:index,:show]
  before_action :set_profile, only: [:update, :destroy]
  before_action :require_permission, only: [:update, :destroy]

  def index

    @profiles = Profile
                .joins(:user)
                .where(:users => {:state => User.states[:active]})
                .where(visible: true)
                .order(created_at: :desc)
                .limit(24)

    @profiles = @profiles.offset(params[:offset]) if params[:offset]

  end

  def show
    if user_signed_in?
      if params[:id]
        @profile = Profile.friendly.find(params[:id])
      else
        @profile = current_user.profile
      end
    else
      @profile = Profile.friendly.find(params[:id])
    end
  end

  def new
    @profile = Profile.new
  end

  def create
    @profile = Profile.new(profile_params)
    @profile.user_id = current_user.id

    respond_to do |format|
      if @profile.save
        format.html { redirect_to @profile, notice: 'Profile was successfully created.' }
        format.json { render :show, status: :created, location: @profile }
      else
        format.html { render :show }
        format.json { render json: @profile.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @profile.update(profile_params)
        format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }
        format.json { render :show, status: :ok, location: @profile }
      else
        format.html { render :show }
        format.json { render json: @profile.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @profile.destroy
    respond_to do |format|
      format.html { redirect_to profile_url, notice: 'Profile was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  def favorite
  end

  private

    def set_profile
      @profile = Profile.friendly.find(params[:id])
    end

    def profile_params
      params.require(:profile).permit(:name, :visible, :website, :details, :soundcloud, :bandcamp, :facebook, :instagram, :twitter, :spotify, :applemusic, :influence_ids => [], :talent_ids => [], :genre_ids => [], :image_attributes => [:id, :image, :imageable_id, :imageable_type, :_destroy])
    end

end
提交

上的

rails console

Started PATCH "/profile/the-national" for 127.0.0.1 at 2016-06-04 20:00:18 -0400
Processing by ProfilesController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"OrPkaYUwDZ6czE4+Y1huD9WrzFvbe5VSbyHIFaQn67lG9NksNBYdNhBFe4JIdQXKxj7RFcREf0sS8H2qNjW5IQ==", "profile"=>{"image_attributes"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007fce521e9d30 @tempfile=#<Tempfile:/var/folders/65/_z6n11pd1mggqwbkhwd8tyqr0000gn/T/RackMultipart20160604-26775-me2shw.png>, @original_filename="social-header.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"profile[image_attributes][image]\"; filename=\"social-header.png\"\r\nContent-Type: image/png\r\n">, "imageable_id"=>"1", "imageable_type"=>"avatar"}}, "commit"=>"Update Profile", "id"=>"the-national"}
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
  Profile Load (0.2ms)  SELECT  "profiles".* FROM "profiles" WHERE "profiles"."slug" = $1  ORDER BY "profiles"."id" ASC LIMIT 1  [["slug", "the-national"]]
  CACHE (0.0ms)  SELECT  "profiles".* FROM "profiles" WHERE "profiles"."slug" = $1  ORDER BY "profiles"."id" ASC LIMIT 1  [["slug", "the-national"]]
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]
   (0.1ms)  BEGIN
  Image Load (0.2ms)  SELECT  "images".* FROM "images" WHERE "images"."imageable_id" = $1 AND "images"."imageable_type" = $2 LIMIT 1  [["imageable_id", 1], ["imageable_type", "Profile"]]
  Influence Load (0.3ms)  SELECT "influences".* FROM "influences" INNER JOIN "influences_profiles" ON "influences"."id" = "influences_profiles"."influence_id" WHERE "influences_profiles"."profile_id" = $1  ORDER BY name asc  [["profile_id", 1]]
  Talent Load (0.3ms)  SELECT "talents".* FROM "talents" INNER JOIN "profiles_talents" ON "talents"."id" = "profiles_talents"."talent_id" WHERE "profiles_talents"."profile_id" = $1  ORDER BY name asc  [["profile_id", 1]]
  Genre Load (0.3ms)  SELECT "genres".* FROM "genres" INNER JOIN "genres_profiles" ON "genres"."id" = "genres_profiles"."genre_id" WHERE "genres_profiles"."profile_id" = $1  ORDER BY name asc  [["profile_id", 1]]
   (0.1ms)  ROLLBACK
  Rendered partials/_header.html.erb (3.8ms)
  Influence Exists (0.3ms)  SELECT  1 AS one FROM "influences" INNER JOIN "influences_profiles" ON "influences"."id" = "influences_profiles"."influence_id" WHERE "influences_profiles"."profile_id" = $1 LIMIT 1  [["profile_id", 1]]
  Influence Exists (0.3ms)  SELECT  1 AS one FROM "influences" INNER JOIN "influences_profiles" ON "influences"."id" = "influences_profiles"."influence_id" WHERE "influences_profiles"."profile_id" = $1 LIMIT 1  [["profile_id", 1]]
  Influence Exists (0.2ms)  SELECT  1 AS one FROM "influences" INNER JOIN "influences_profiles" ON "influences"."id" = "influences_profiles"."influence_id" WHERE "influences_profiles"."profile_id" = $1 LIMIT 1  [["profile_id", 1]]
  Rendered partials/_loading_circle.html.erb (0.1ms)
  Rendered partials/_chunk_tags.html.erb (9.8ms)
  Talent Exists (0.3ms)  SELECT  1 AS one FROM "talents" INNER JOIN "profiles_talents" ON "talents"."id" = "profiles_talents"."talent_id" WHERE "profiles_talents"."profile_id" = $1 LIMIT 1  [["profile_id", 1]]
  Talent Exists (0.2ms)  SELECT  1 AS one FROM "talents" INNER JOIN "profiles_talents" ON "talents"."id" = "profiles_talents"."talent_id" WHERE "profiles_talents"."profile_id" = $1 LIMIT 1  [["profile_id", 1]]
  Talent Exists (0.2ms)  SELECT  1 AS one FROM "talents" INNER JOIN "profiles_talents" ON "talents"."id" = "profiles_talents"."talent_id" WHERE "profiles_talents"."profile_id" = $1 LIMIT 1  [["profile_id", 1]]
  Rendered partials/_loading_circle.html.erb (0.0ms)
  Rendered partials/_chunk_tags.html.erb (8.3ms)
  Genre Exists (0.2ms)  SELECT  1 AS one FROM "genres" INNER JOIN "genres_profiles" ON "genres"."id" = "genres_profiles"."genre_id" WHERE "genres_profiles"."profile_id" = $1 LIMIT 1  [["profile_id", 1]]
  Genre Exists (0.2ms)  SELECT  1 AS one FROM "genres" INNER JOIN "genres_profiles" ON "genres"."id" = "genres_profiles"."genre_id" WHERE "genres_profiles"."profile_id" = $1 LIMIT 1  [["profile_id", 1]]
  Genre Exists (0.2ms)  SELECT  1 AS one FROM "genres" INNER JOIN "genres_profiles" ON "genres"."id" = "genres_profiles"."genre_id" WHERE "genres_profiles"."profile_id" = $1 LIMIT 1  [["profile_id", 1]]
  Rendered partials/_loading_circle.html.erb (0.0ms)
  Rendered partials/_chunk_tags.html.erb (6.0ms)
  Rendered profiles/show.html.erb within layouts/application (46.4ms)
  Rendered partials/_favicons.html.erb (56.4ms)
  Rendered partials/_social_svgdefs.html.erb (0.1ms)
  Rendered partials/_mini_svgdefs.html.erb (0.1ms)
Completed 200 OK in 225ms (Views: 153.8ms | ActiveRecord: 9.1ms)

0 个答案:

没有答案