Ruby on rails 未定义的方法'first';对于#<;文章:0x5b0a4d8>;
我正在创建一个带有标签的博客。使用Mongodb。 我在提交带有标签的新文章时遇到了这个错误。而新的艺术并没有被创造出来。如果我没有在表单中添加任何标记,那么就创建了文章 ArticlesController中的命名错误#创建 未定义的方法“first”# Rails.root:c:/Sites/blogK 应用程序跟踪|框架跟踪|完整跟踪 app/models/article.rb:18:inRuby on rails 未定义的方法'first';对于#<;文章:0x5b0a4d8>;,ruby-on-rails,Ruby On Rails,我正在创建一个带有标签的博客。使用Mongodb。 我在提交带有标签的新文章时遇到了这个错误。而新的艺术并没有被创造出来。如果我没有在表单中添加任何标记,那么就创建了文章 ArticlesController中的命名错误#创建 未定义的方法“first”# Rails.root:c:/Sites/blogK 应用程序跟踪|框架跟踪|完整跟踪 app/models/article.rb:18:in所有标签 app/controllers/articles\u controller.rb:22:in
所有标签
app/controllers/articles\u controller.rb:22:in
new'
app/controllers/articles\u controller.rb:22:in'create'
第1.rb条
class Article
include Mongoid::Document
has_many :comments, dependent: :destroy
field :title, type: String
field :text, type: String
embeds_many :taggings
embeds_many :tags
def all_tags=(tags_string)
tag_names = tags_string.split(",").collect{|s| s.strip.downcase}.uniq
new_or_found_tags = tag_names.collect { |name| Tag.find_or_create_by(name: name) }
self.tags = new_or_found_tags
end
def all_tags
self.tags.collect do |tag|
tag.name
end.join(", ")
end
validates :title, presence: true,
length: { minimum: 5 }
end
tag.rb
class Tag
include Mongoid::Document
field :name, type: String
embeds_many :taggings
embeds_many :articles
end
tagging.rb
class Tagging
include Mongoid::Document
embedded_in :article
embedded_in :tag
end
article_controller.rb
class ArticlesController < ApplicationController
http_basic_authenticate_with name: "dhh", password: "secret", except: [:index, :show]
def index
@articles = Article.all
end
def show
@article = Article.find(params[:id])
end
def new
@article = Article.new
end
def edit
@article = Article.find(params[:id])
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render 'new'
end
end
def update
@article = Article.find(params[: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, :all_tags)
end
end
class-ArticlesController
_form.html.erb
<%= form_for @article do |f| %>
<% if @article.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(@article.errors.count, "error") %> prohibited
this article from being saved:
</h2>
<ul>
<% @article.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p><%= f.text_field :all_tags, placeholder: "Tags separated with comma" %></p>
<p>
<%= f.submit %>
</p>
<% end %>
禁止
要保存此文章,请执行以下操作:
您是否安装了“pry”gem?你的all\u tags=(tags\u string)
方法中似乎发生了错误,因此我只需在其中放置一对binding.pry
断点,直到你弄清楚它到底在哪里失败。你是否安装了“pry”gem?看起来错误发生在您的all\u tags=(tags\u string)
方法中,因此我只需在其中放置一对绑定。撬动
断点,直到您准确地找出失败的位置