我最近为正在开发的应用程序的用户创建了一个配置文件页面,但在此过程中我注意到该故事的URL最初与用户页面上的相同故事略有不同。例如,普通网址是" http://localhost:3000/genres/action/stories/37"虽然它是" http://localhost:3000/genres/absurdist/stories/37"同时故事最初属于"动作类型"而不是"荒诞的"。同时,这两个网址指向正常的故事页面。
genre.rb
class Genre < ApplicationRecord
belongs_to :user
has_many :stories, dependent: :destroy
is_impressionable
extend FriendlyId
friendly_id :name, use: :slugged
def should_generate_new_friendly_id?
name_changed?
end
end
story.rb
class Story < ApplicationRecord
belongs_to :genre
belongs_to :user
has_many :episodes, dependent: :destroy
is_impressionable
extend FriendlyId
friendly_id :title, use: :slugged
def should_generate_new_friendly_id?
title_changed?
end
has_attached_file :image, size: { less_than: 1.megabyte }, styles: { medium: "300x300#", wide: "200x400#" }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
scope :of_followed_users, -> (following_users) { where user_id: following_users }
end
profiles_controller
class ProfilesController < ApplicationController
before_action :find_user
before_action :find_genre
before_action :owned_profile, only: [:edit, :update]
before_action :authenticate_user!
def show
@stories = User.find_by(user_name: params[:user_name]).stories.order('created_at DESC')
impressionist(@user)
end
def edit
end
def update
if @user.update(profile_params)
flash[:success] = 'Your profile has been updated.'
redirect_to profile_path(@user.user_name)
else
@user.errors.full_messages
flash[:error] = @user.errors.full_messages
render :edit
end
end
private
def profile_params
params.require(:user).permit(:avatar, :bio)
end
def find_user
@user = User.find_by(user_name: params[:user_name])
end
def find_genre
@genre = Genre.friendly.find_by(params[:slug])
end
def owned_profile
@user = User.find_by(user_name: params[:user_name])
unless current_user == @user
flash[:alert] = "That profile does not belong to you"
redirect_to root_path
end
end
end
个人资料显示
<div class="container my-5">
<div class="card-columns clearfix">
<%= render @user.stories %>
</div>
</div>