我想添加"类别"功能。 我关联了article.rb和category.rb。 但是,未定义的方法`类别'为零:NilClass在场。 我不知道。如果您知道任何解决方案,请告诉我。
Index.html.erb
<% unless @article.categories.blank? %>
<% @articles.categories.each do |category|%>
<%= link_to category.name,article_path(category_id:category.id)%>
<%end%>
<%end%>
article.rb
class Article < ApplicationRecord
scope :from_category, -> (category_id) { where(id: article_ids = ArticleCategory.where(category_id: category_id).select(:article_id))}
validates :title, presence: true
validates :content, presence: true
mount_uploader :image,ImageUploader
has_many :categories, through: :article_categories
has_many :article_categories, dependent: :destroy
def save_categories(tags)
current_tags = self.categoires.pluck(:name) unless self.categories.nil?
old_tags = current_tags - tags
new_tags = tags - current_tags
old_tags.each do |old_name|
self.categories.delete Category.find_by(name:old_name)
end
new_tags.each do |new_name|
article_category = Category.find_or_create_by(name:new_name)
self.categories << article_category
end
end
end
category.rb
class Category < ApplicationRecord
validates :name,presense: true,length:{maximum:50}
has_many :articles,through: :article_categories
has_many :article_categories,dependent: :destroy
end
article_category.rb
class ArticleCategory < ApplicationRecord
belongs_to :article
belongs_to :category
validates :article_id,presense:true
validates :category_id,presense:true
end
articles_controller.rb
class ArticlesController < ApplicationController
before_action :set_post, only: [:show,:edit,:update]
before_action :authenticate_user!, :except => [:index,:show]
before_action :set_article_tags_to_gon, only: [:edit]
def index
if params[:category_id]
@selected_category = Category.find(params[:category_id])
@articles= Article.from_category(params[:category_id]).page(params[:page])
else
@articles= Article.all.page(params[:page])
end
@articles = Article.page params[:page]
end
def show
end
def new
@article = Article.new
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to articles_path
else
render 'articles/new'
end
end
def edit
@category_list = @article.categories.pluck(:name).join(",")
end
def update
if @article.update(article_params)
redirect_to articles_path
else
redirect_to 'edit'
end
end
private
def article_params
params[:article].permit(:title,:content,:image,:tag_list,:category)
end
def set_post
@article = Article.find(params[:id])
end
答案 0 :(得分:0)
您在nil
对象上调用类别,在本例中为@article
。你的意思是在@articles
上打电话吗?
如果没有,则需要在控制器的@article
操作中定义index
。