Отображение элемента с определенным параметром в индексе - PullRequest
0 голосов
/ 01 февраля 2019

Я создаю сайт для поэзии.Существует два типа поэзии: знаменитая или любительская.

Я построил функции CRUD для отображения всех поэзий (известных и любительских, а не различий), и это работает так, как задумано (см. Код PoetrisController ниже).

Теперь я хочу дать возможность пользователю выбирать, хочет ли он видеть только любительские или известные стихи.Обычно пользователь нажимает ссылку «Любитель» или «Знаменитый» в навигационной панели, и он перенаправляется на новую страницу с перечнем только любительских или известных стихов.

У меня вопрос: должен ли я создать другой контроллер (например, PoetriesFamousController) и создание внутри него индексной функции для отображения только известных стихов или есть способ использовать уже существующий PoetriesController для отображения только «известных стихов», если пользователь нажимает ссылку в навигационной панели?

PoetriesController:

 class PoetriesController < ApplicationController
 skip_after_action :verify_authorized, only: [:home, :about, :newsletter, :disclaimer, :new, :create]

  skip_before_action :authenticate_user!, only: [:home, :about, :newsletter, :disclaimer, :new, :create]

  before_action :set_poetry, only: [:show, :edit, :update, :destroy,]
  before_action :authenticate_user!, except: [:index, :amateur_poetries]

  def index
    if params[:search]
      @poetries = policy_scope(Poetry).search(params[:search]).order("created_at DESC").limit(30)
    else
      @poetries = policy_scope(Poetry).order("RANDOM()").limit(30)
    end
  end


  def show
    authorize @poetry
  end

  def new
    @poetry = Poetry.new
  end

  def create
    Poetry.create(poetry_params)
    redirect_to poetries_path
  end

  def edit
    authorize @poetry
  end

  def update
    @poetry.save
    redirect_to poetry_path(@poetry)
  end

  def destroy
    @poetry.destroy
    redirect_to poetries_path
  end



  private

  def poetry_params
    params.require(:poetry).permit(:title, :author, :body, :poster, :country)
  end

  def set_poetry
    @poetry = Poetry.find(params[:id])
  end
end

Poetries.rb

class Poetry < ApplicationRecord
  def self.search(search)
    where("lower(title) LIKE ? OR lower(author) LIKE ? OR lower(country) LIKE ? OR lower(born) LIKE ?", "%#{search}%", "%#{search}%", "%#{search}%", "%#{search}%")
  end
end

Routes.rb

  get 'poetries', to: 'poetries#index', as: :poetries
  get "poetries/new", to: "poetries#new"
  post   "poetries", to: "poetries#create"
  get "poetries/:id/edit", to: "poetries#edit"
  patch "poetries/:id", to: "poetries#update"
  get 'poetries/:id', to: 'poetries#show', as: :poetry
  delete "poetries/:id", to: "poetries#destroy"

Ответы [ 2 ]

0 голосов
/ 01 февраля 2019

вот некоторая идея для вашей проблемы

на ваш взгляд (примерная идея)

poetries type: 
<%= select_tag :poetries_type, options_for_select(["Famous","Amateur"]), include_blank: true, :class => 'form-control'  %>

в вашем контроллере

def index
  if params[:search]
    if params[:poetries_type] == "Famous"
      @poetries = Poetry.famous.search(params[:search]).order("created_at DESC").limit(30)
    elsif params[:poetries_type] == "Amateur"
      @poetries = Poetry.amateur.search(params[:search]).order("created_at DESC").limit(30)
    else
      @poetries = Poetry.search(params[:search]).order("created_at DESC").limit(30)
    end
  else
    @poetries = policy_scope(Poetry).order("RANDOM()").limit(30)
  end
end

Poetries.rb, добавьте дваПростор для знаменитого любителя

def self.amateur
  where("poster != ?","Admin")
end 

def self.famous
  where("poster = ?","Admin")
end
0 голосов
/ 01 февраля 2019

Самое простое было бы добавить еще два действия к вашему контроллеру.

def famous
  @poetries = #get the famous ones
  render :index
end
def amateur
  @poetries = #get the amateur ones
  render :index
 end

Затем обновите ваши маршруты

 get 'poetries', to: 'poetries#index', as: :poetries
 get 'poetries/famous', to: 'poetries#famous'
 get 'poetries/amateur', to: 'poetries#amateur
 # rest of the routes
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...