Fliendly_ID - URL не отображается

Я новичок в ROR и работаю над небольшим проектом. Недавно я добавил дружественные идентификационные камни и следовал инструкциям в документации. Но я не могу заставить работать URL. Я добавил дружественный идентификатор в модель сообществ, которая в основном является моделью ваших сообщений.

Код маршрута:

class Community < ActiveRecord::Base

extend FriendlyId
friendly_id :title, use: [:slugged, :history]




  validates :title, :length => { :minimum => 5 }

has_attached_file :post_image, :styles => 
           { :medium => "300x300>", :thumb => "100x100>", :large => "1280x720", :headline => "1280x720"}

validates_attachment_content_type :post_image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]

belongs_to :member 
has_many :comments
scope :newest_first, lambda { order("communities.created_at DESC")}
scope :without_community, lambda{|community| community ? {:conditions => ["community.id != ?", @community.id]} : {} }

# def to_param

#   "#{id}-#{title.parameterize}"

# end

end

Я даже попытался to_param, чтобы получить URL-адреса. Но ничего не работает.

Код контроллера:

class CommunitiesController < ApplicationController
  before_action :set_community, only: [:show, :edit, :update, :destroy]
  layout "community"
  before_filter :authenticate_member!, except: [:index, :show]
  require 'will_paginate/array'

  # GET /communities
  # GET /communities.json
  def index
    @communities = Community.newest_first.friendly.where(params[:id]).paginate(page: params[:page], per_page: 9)
  end

  # GET /communities/1
  # GET /communities/1.json
  def show
    @communities = Community.newest_first.friendly.where(params[:title]).paginate(page: params[:page], per_page: 5).where('id NOT IN (?)', @community.id)

  end

  # GET /communities/new
  def new
    @community = Community.new({:member_id => current_member.id})
  end

  # GET /communities/1/edit
  def edit
  end

  # POST /communities
  # POST /communities.json
  def create
    @community = Community.new(community_params)

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

  # PATCH/PUT /communities/1
  # PATCH/PUT /communities/1.json
  def update
    respond_to do |format|
      if @community.update(community_params)
        format.html { redirect_to @community, notice: 'Post: #{@community.title.capitalize} was successfully updated.' }
        format.json { render :show, status: :ok, location: @community }
      else
        format.html { render :edit }
        format.json { render json: @community.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /communities/1
  # DELETE /communities/1.json
  def destroy
    @community.destroy
    respond_to do |format|
      format.html { redirect_to communities_url, notice: 'Post: #{@community.title.capitalize} was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_community
      @community = Community.friendly.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def community_params
      params.require(:community).permit(:name,:post_image, :title, :content, :member_id)
    end
end

Но если я введу URL-адрес, например http://localhost:3000/communities/post.title, я смогу перейти непосредственно к сообщению. Это означает, что слизни были созданы, и они работают вроде. Но я не могу отобразить их в URL. Я перепробовал много перестановок и комбинаций, но ничего не помогло.

Буду очень признателен за любую помощь. Дайте мне знать, если вам нужен какой-то другой конкретный код.

К вашему сведению: Код миграции:

class AddSlugToCommunities < ActiveRecord::Migration
  def change
    add_column :communities, :slug, :string, limit: 191
    add_index :communities, :slug, unique: true
  end
end

Код миграции Friendly_ID:

class CreateFriendlyIdSlugs < ActiveRecord::Migration
  def change
    create_table :friendly_id_slugs do |t|
      t.string   :slug,           :null => false, limit: 191
      t.integer  :sluggable_id,   :null => false
      t.string   :sluggable_type, :limit => 50
      t.string   :scope, limit: 191
      t.datetime :created_at
    end
    add_index :friendly_id_slugs, :sluggable_id
    add_index :friendly_id_slugs, [:slug, :sluggable_type]
    add_index :friendly_id_slugs, [:slug, :sluggable_type, :scope], :unique => true
    add_index :friendly_id_slugs, :sluggable_type
  end
end

1 ответ

Решение

Углубился в код и обнаружил, что были сделаны слизняки. Просто URL не был правильно связан. Внесены некоторые изменения в ссылки на использование слагов вместо:id, чтобы все заработало.

В любом случае спасибо @uzaif

Другие вопросы по тегам