D
D
Denis2018-05-30 12:08:14
Ruby on Rails
Denis, 2018-05-30 12:08:14

How to pass create and destroy for two hotel and room models in one controller?

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

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
Zaporozhchenko Oleg, 2018-05-30
@c3gdlk

use nestred_resources guides.rubyonrails.org/routing.html#nested-resources and depending on the parameter that will come choose the class Room or Hotel

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question