В Rail отображаются только модели, родительская модель которых принадлежит текущему пользователю. - PullRequest
0 голосов
/ 30 апреля 2019

Я создаю приложение на Rails 5 и столкнулся с проблемой, когда в моем модельном индексе Projects отображаются проекты для всех пользователей на платформе.

Структура моего приложения состоит в том, что у меня есть модель Project.которая принадлежит модели транспортного средства, которая принадлежит пользователю.Когда я захожу в свой индекс проектов, все проекты других пользователей также отображаются.Как получить проекты, в которых родительская модель транспортного средства имеет идентификатор пользователя для текущего пользователя?Или было бы лучше также добавить идентификатор пользователя в класс проекта.

Вот мой контроллер проекта:

class ProjectsController < ApplicationController
  before_action :set_project, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!

  # GET /projects
  # GET /projects.json
  def index
    @projects = Project.where(completed: 'false')
  end

  def all_projects
    @projects = Project.all
    render :index
  end

  def finished_projects
    @projects = Project.where(completed: 'true')
    render :index
  end

  # GET /projects/1
  # GET /projects/1.json
  def show
    @back_url = session[:my_previous_url]
  end

  # GET /projects/new
  def new
    @project = Project.new(vehicle_id: params[:vehicle_id])
    @vehicles = Vehicle.where(user: current_user)
  end

  # GET /projects/1/edit
  def edit
    @vehicles = Vehicle.where(user: current_user)
  end

  # POST /projects
  # POST /projects.json
  def create
    @project = Project.new(project_params)

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

  # PATCH/PUT /projects/1
  # PATCH/PUT /projects/1.json
  def update
    respond_to do |format|
      if @project.update(project_params)
        format.html { redirect_to @project, notice: 'Project was successfully updated.' }
        format.json { render :show, status: :ok, location: @project }
      else
        format.html { render :edit }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /projects/1
  # DELETE /projects/1.json
  def destroy
    @project.destroy
    respond_to do |format|
      format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def project_params
      params.require(:project).permit(:title, :details, :vehicle_id, :completed)
    end
end

Я использую devise для аутентификации, если это имеет какое-либо значение.Спасибо!

1 Ответ

2 голосов
/ 30 апреля 2019

Давайте добавим несколько объединений и условие where для соответствия текущему пользователю. Некоторые альтернативы.

пользователи не присоединяются

@projects = Project.joins(:vehicle).
    where(vehicles: {user: current_user})

с присоединением пользователя

@projects = Project.joins(vehicle: :user).
    where(users: {id: current_user.id})
...