Проблемы при создании новой статьи - PullRequest
0 голосов
/ 11 марта 2019

Я пытаюсь реализовать категории в своем блоге Ruby on Rails, но получаю сообщение об ошибке при попытке создать новую статью.Не удалось найти статью без идентификатора, ActiveRecord: RecordNotFound в ArticlesController # new

Вот мой код контроллера статьи:

class ArticlesController < ApplicationController
#http_basic_authenticate_with name: "orko", password: "1234567",
#except: [:index, :show, :search]

before_action :edit, :admin_authorize, :except => [:index, :show, :search]

  def index
    if params[:category].blank?
      @articles = Article.all.order("created_at DESC")
    else
      @category_id = Category.find_by(name: params[:category]).id
      @articles = Article.where(category_id: @category_id).order("created_at DESC")
    end
  end

  def new
    @article = Article.new
    @categories = Category.all.map{|c| [c.name, c.id]}
  end

  def show
    @article = Article.find(params[:id])
  end

  def create
    @article = Article.new(article_params)
    @article.category_id = params[:category_id]

    respond_to do |format|
      if article.save
        format.html { redirect_to @article, notice: "Article was successfully created!" }
        format.json { render :show, status: :created, location: @article }
      else
        format.html { render :new}
        format.json {render json: @article.errors, status: :unprocessable_entity}
      end
    end
  end

  def edit
    @article = Article.find(params[:id])
    @categories = Category.all.map { |c| [c.name, c.id]}
  end

  def search
    if params[:search].blank?
      @articles = Article.all
    else
      @articles = Article.search(params)
    end
  end

  def update
    @article = Article.find(params[:id])
    @article.category_id = params[:category_id]
    if @article.update(article_params)
      redirect_to @article
    else
      render 'edit'
    end
  end

  def destroy
    @article = Article.find(params[:id])
    @article.destroy
    redirect_to articles_path
  end

private
  def article_params
    params.require(:article).permit(:title, :text, :search, :music, :movie, :photo)
  end

  def find_article
    @article = Article.find(params[:id])
  end
end

Модель товара:

class Article < ApplicationRecord
  belongs_to :category
  has_many :comments, dependent: :destroy
  validates :title, presence: true, length: {minimum: 3}
  validates :text, presence: true, length: {minimum: 3}
  validates :category_id, presence: true

  #For photo special characters \A, \w, \z
  has_attached_file :photo, styles: {large: "450x450>", thumb: "50x50#"}
  validates_attachment_content_type :photo, content_type: /\Aimage\/.*\z/

  #For music upload
  has_attached_file :music
  validates_attachment :music,
  :content_type => {:content_type => ["audio/mpeg","audio/mp3"]},
  :file_type => {:matches => [/mp3\Z/]}

  #For movie
  has_attached_file :movie, :styles =>
  {
    :medium => {:geometry => "640x480", :format=> 'mp4'},
    :thumb => {:geometry => "100x50", :format => 'jpg', :time => 10}
  }, :processor => [:transcoder]
  validates_attachment_content_type :movie, content_type: /\Avideo\/.*\z/

  def self.search(params)
    articles = Article.where("text LIKE ? or title LIKE ?", "%#{params[:search]}%",
                                                            "%#{params[:search]}%") if params[:search].present?
    articles # returns the articles containing the search words
  end
end

И модель категории:

class Category < ApplicationRecord
  has_many :articles
end

А вот мой файл маршрута:

Rails.application.routes.draw do
#  get 'sessions/new'

  resources :sessions
  resources :users
  get 'welcome/index'

  resources :articles do
    resources :comments
    collection do
      get :search #creates a new path for searching
    end
  end
  resources :subscribers
  root 'welcome#index'
  get 'pages/about' => 'application#show'
end

Ответы [ 2 ]

1 голос
/ 11 марта 2019

В эти параметры вы добавили: метод поиска. Пожалуйста, удалите метод поиска и проверьте его.

   > params.require(:article).permit(:title, :text, :search, :music,
    > :movie, :photo)

Просто попробуйте создать статью в консоли rails.

0 голосов
/ 11 марта 2019

Вы вызываете метод edit для before_action, попробуйте удалить его или добавьте new & create в массив except.

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