controllers/pictures_controller.rb
class PicturesController < ApplicationController
def create
@room = Room.find(params[:imageable_id])
if params[:images]
params[:images].each do |img|
@room.pictures.create(image: img)
end
@pictures = @room.pictures
redirect_back(fallback_location: request.referer, notice: "Сохранено...")
end
end
def destroy
@picture = Picture.find(params[:id])
@room = @picture.room
@picture.destroy
@pictures = Picture.where(imageable_id: @imageable.id)
respond_to :js
end
end
models/room.rb
class Room < ApplicationRecord
enum instant: {Запрос: 0, Мгновенное: 1}
belongs_to :user
belongs_to :hotel
has_many :pictures, :as => :imageable
has_many :reservations
has_many :guest_reviews
has_many :calendars
geocoded_by :address
after_validation :geocode, if: :address_changed?
validates :home_type, presence: true
validates :room_type, presence: true
validates :accommodate, presence: true
validates :bed_room, presence: true
validates :bath_room, presence: true
def cover_photo(size)
if self.pictures.length > 0
self.pictures[0].image.url(size)
else
"blank.jpg"
end
end
def average_rating
guest_reviews.count == 0 ? 0 : guest_reviews.average(:star).round(2).to_i
end
end
models/hotel.rb
class Hotel < ApplicationRecord
belongs_to :user
has_many :pictures, :as => :imageable
validates :hotel_type, presence:true
validates :num_room, presence:true
validates :food, presence:true
geocoded_by :address
after_validation :geocode, if: :address_changed?
def cover_photo(size)
if self.pictures.length > 0
self.pictures[0].image.url(size)
else
"blank.jpg"
end
end
end
models/picture.rb
class Picture < ApplicationRecord
belongs_to :imageable, :polymorphic => true
has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
end