Rails / friendly_id-带有嵌套路线的子弹

时间:2018-08-22 04:19:38

标签: ruby-on-rails

我正在尝试获取friendly_id以与嵌套模型一起使用。目前,它可以与根模型一起使用,但是当我转到嵌套模型时,它将恢复为显示id而不是段标。

所以不是

www.example.com/coins/slug-name/events/:id

我最终得到

www.example.com/coins/:id/events/:id

我需要对事件模型/控制器执行什么操作才能使其显示出弹头?

coin.rb

class Coin < ApplicationRecord
  extend FriendlyId
  friendly_id :link_name, use: [:slugged, :finders, :history]
  has_many :events, dependent: :destroy
...

coin_controller.rb

class CoinsController < ApplicationController

  load_and_authorize_resource param_method: :question_params
  before_action :find_coin, only: [:edit, :update, :destroy ]
  before_action :authenticate_user!, except: [:index, :show]
  before_action :find_user

  ...
  def show
    @coin = Coin.friendly.find(params[:id])
    @coin_events = @coin.events

  ...

  private
    def find_coin
      @coin = Coin.friendly.find(params[:id])
    end

    ..
end

event.rb

class Event < ApplicationRecord
  acts_as_votable
  belongs_to :user
  belongs_to :coin
  scope :later_events, Proc.new { |current = DateTime.now, limit = 7| where('date > ?', current).order("date ASC").limit(limit) }
  scope :prior_events, Proc.new { |current = DateTime.now, limit = 3| where('date < ?', current).order("date DESC").limit(limit) }
end

events_controller.rb

class EventsController < ApplicationController

  before_action :find_event, only: [:show, :edit, :update, :destroy ]
  before_action :find_coin
  before_action :authenticate_user!

  def index  
    @events = Event.where(coin_id: @coin.id).order("created_at DESC")
  end

  def show
    authorize! :read, @event
  end

  def new
    @event = current_user.events.build
  end

  def create
    @event = current_user.events.build(event_params)
    @event.coin = @coin
    if @event.save!
      redirect_to coin_event_path(@coin.id, @event.id)
    else
      render 'new'
    end
  end

  def edit
  end

  def update
    authorize! :update, @event
    if @event.update(event_params)
      redirect_to coin_event_path(@coin.id, @event.id)
    else
      redirect_to 'edit'
    end
  end

  def destroy
    authorize! :destroy, @event
    @event.destroy
    redirect_to coin_events_path(@coin.id)
  end

  def approve
    @event.update_attribute(:approved, true)
  end

  def upvote
    @event = Event.find(params[:id] )
    @event.upvote_by current_user
    redirect_back(fallback_location: root_path)
  end

  def downvote
    @event = Event.find(params[:id] )
    @event.downvote_by current_user
    redirect_back(fallback_location: root_path)
  end

  def pending
    @events = Event.where(coin_id: @coin.id).order("created_at DESC")
  end

  private

    def find_event
      @event = Event.find(params[:id])
    end

    def find_coin
      @coin = Coin.friendly.find(params[:coin_id])
    end

    def event_params
      params.require(:event).permit(:content, :link, :date, :time, :city, :state, :country, :description, :accepted)
    end
end

0 个答案:

没有答案