Пользователи могут видеть свойства владельцев Rails 5.2 - PullRequest
0 голосов
/ 30 января 2020

Я разрабатывал приложение вроде платформы Real Estate . Но я столкнулся с трудностями сына в отношении определенной c функциональности.

У меня есть два типа пользователей: Владельцы и Пользователи . Владелец создает свойства, и пользователь, очевидно, должен визуализировать их и взаимодействовать с ними. Оба пользователя разработаны с использованием devise , владельцы могут успешно создавать свойства, , но пользователи не могут их видеть .

Итак, когда я захожу как Пользователь , я хочу увидеть некоторые свойства, которые были созданы владельцами, независимо от того, в каком порядке они там отображены. Я пришел с этой проблемой, потому что мне нужно создать фильтр, чтобы Пользователи могли найти определенные c свойства, но никакой фильтр не может быть выполнен, если пользователь не может видеть свойства.

Итак, это мой код:

Create_properties Миграция

class CreateProperties < ActiveRecord::Migration[5.2]
  def change
    create_table :properties do |t|
      t.string :name
      t.text :description
      t.integer :price
      t.string :address
      t.float :latitude
      t.float :longitude



      t.references :owner
      t.timestamps
    end
    add_index :properties, [:id, :created_at]
  end
end

Properties_controller.rb

class PropertiesController < ApplicationController
  before_action :set_property, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_owner!

  # GET /properties
  # GET /properties.json
  def index
    @properties = Property.all
  end

  # GET /properties/1
  # GET /properties/1.json
  def show

  end

  # GET /properties/new
  def new
    @property = current_owner.properties.build
    @property.amenities.build
    @property.services.build
    @property.build_propertytype

  end

  # GET /properties/1/edit
  def edit
  end

  # POST /properties
  # POST /properties.json
  def create
    @property = current_owner.properties.build(property_params)

    respond_to do |format|
      if @property.save
        format.html { redirect_to @property, notice: 'Tu propiedad ha sido creada!' }
        format.json { render :show, status: :created, location: @property }
      else
        format.html { render :new }
        format.json { render json: @property.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /properties/1
  # PATCH/PUT /properties/1.json
  def update
    respond_to do |format|
      if @property.update(property_params)
        format.html { redirect_to @property, notice: 'La propiedad ha sido actualizada.' }
        format.json { render :show, status: :ok, location: @property }
      else
        format.html { render :edit }
        format.json { render json: @property.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /properties/1
  # DELETE /properties/1.json
  def destroy
    @property.destroy
    respond_to do |format|
      format.html { redirect_to properties_url, notice: 'La propiedad ha sido eliminada!' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_property
      @property = Property.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def property_params
      params.require(:property).permit(:id, :description, :price, :sharable, :address, { pictures: [] }, amenities_attributes: [:id, :bathroom, :room, :pool, :gym, :kitchen, :terrace, :balcony, :living_room, :garage, :parking_lot, :green_areas], propertytype_attributes: [ :apartment, :building, :office, :local_comercial, :house, :terrain ], services_attributes: [:wifi, :electricity, :gas, :guard, :air_conditioning, :water, :include_furniture])
    end
end

Модель свойства

class Property < ApplicationRecord
    belongs_to :owner
    has_many :amenities
    has_many :services
    has_one :propertytype

    accepts_nested_attributes_for :propertytype
    accepts_nested_attributes_for :amenities
    accepts_nested_attributes_for :services

    mount_uploaders :pictures, PropertypictureUploader
end

Модель пользователя

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable, :confirmable, :trackable

  validates :rfc, presence: true

end

Итак, как я могу заставить пользователя видеть некоторые свойства? Буду признателен за помощь!

1 Ответ

1 голос
/ 30 января 2020

ниже - пример, основанный на вашей информации выше, чтобы найти свойства, созданные владельцами

def index
  @properties = Owner.find_by_name('John').properties
  # this will list properties that owned by John
  @properties = Property.joins(:owner).all
  # this will list properties that has owner
  @properties = Property.joins(:owner).where('properties.price <= ?',1000000)
  # this will list properties that has owner and price is below 1 million
end
...