У меня есть конкретный вопрос. Поэтому я пойму, если мне никто не поможет. :) В любом случае, спасибо заранее! Как я могу реорганизовать этот код с помощью ресурсов и спокойного соглашения? Особенно я имею в виду render_with_hashtags_of_question(text)
и render_with_hashtags_of_answer(text)
методы и соответствующий маршрут get '/questions/hashtag/:name', to: 'questions#hashtags'
Rails URL-адреса маршрутов и маршрутизация ресурсов
Вопрос модель:
require 'active_support/all'
class Question < ActiveRecord::Base
TAG_REGEX = (/#[\p{L}_]+/)
belongs_to :user
belongs_to :author, class_name: 'User'
has_and_belongs_to_many :tags
validates :text, :user, presence: true
validates :text, length: { maximum: 255 }
after_save :add_hashtags
after_commit do
self.tags.clear
add_hashtags
end
private
def add_hashtags
hashtags = self.text.scan(TAG_REGEX)
hashtags << self.answer.scan(TAG_REGEX) if self.answer.present?
hashtags.uniq.map do |hashtag|
tag = Tag.find_or_create_by(name: hashtag.to_s.mb_chars.downcase.delete('#[]"'))
self.tags << tag
end
end
end
question_controller.rb:
class QuestionsController < ApplicationController
before_action :load_question, only: [:show, :edit, :update, :destroy]
before_action -> { authorize_owner(@question.user) }, only: [:update, :destroy]
def index; end
def show; end
def edit; end
def hashtags
tag = Tag.find_by(name: params[:name])
@questions = tag.questions
end
def create
@question = Question.new(question_params)
@question.author = current_user if current_user.present?
if check_captcha(@question) && @question.save
redirect_to user_path(@question.user), notice: 'Question was successfully created.'
else
render :edit
end
end
def update
if check_captcha(@question) && @question.update(question_params)
redirect_to user_path(@question.user), notice: 'Question was successfully edited.'
else
render :edit
end
end
def destroy
user = @question.user
@question.destroy
redirect_to user_path(user), notice: 'Question was successfully deleted.'
end
private
def load_question
@question = Question.find(params[:id])
end
def authorize_owner(user)
reject_user unless user == current_user
end
def question_params
if current_user.present? && params[:question][:user_id].to_i == current_user.id
params.require(:question).permit(:user_id, :text, :answer, :tag_id, :tag, { tag_ids: [] }, :tag_ids)
else
params.require(:question).permit(:user_id, :text, :tag_id, :tag, { tag_ids: [] }, :tag_ids)
end
end
def check_captcha(model)
verify_recaptcha(model: model) unless current_user.present?
end
end
question_helper.rb:
require 'active_support/all'
module QuestionsHelper
TAG_REGEX = (/#[\p{L}_]+/)
def render_with_hashtags_of_question(text)
text.gsub(TAG_REGEX){
|word| link_to word, "https://stackoverflow.com/questions/hashtag/#{word.mb_chars.downcase.delete('#')}"
}.html_safe
end
def render_with_hashtags_of_answer(answer)
answer&.gsub(TAG_REGEX){
|word| link_to word, "https://stackoverflow.com/questions/hashtag/#{word.mb_chars.downcase.delete('#')}"
}&.html_safe
end
end
routes.rb:
Rails.application.routes.draw do
root 'users#index'
resources :users
resource :session, only: [:new, :create, :destroy]
resources :questions, except: [:new] , :index]
get '/questions/hashtag/:name', to: 'questions#hashtags'
end
schema.rb:
ActiveRecord::Schema.define(version: 20161227111328) do
create_table "questions", force: :cascade do |t|
t.string "text"
t.string "answer"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.integer "author_id"
end
add_index "questions", ["user_id"], name: "index_questions_on_user_id"
create_table "questions_tags", id: false, force: :cascade do |t|
t.integer "question_id"
t.integer "tag_id"
end
add_index "questions_tags", ["question_id"], name: "index_questions_tags_on_question_id"
add_index "questions_tags", ["tag_id"], name: "index_questions_tags_on_tag_id"
create_table "tags", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "name"
t.string "username"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "email"
t.string "password_hash"
t.string "password_salt"
t.string "avatar_url"
t.text "background_color"
t.text "font_color"
end
end
Я изо всех сил старался, чтобы решить эту проблему в течение нескольких дней честно, но в итоге не получили ничего.
Вы должны смотреть вверх [подстановочные маршрутизация] (HTTP://guides.rubyonrails.org/routing.html#route-globbing-and-wildcard-segments). –
Я решил проблему. В любом случае, спасибо за ответ! :) –