未定义的方法`first'for#<article:0x5b0a4d8>

时间:2016-03-11 17:29:40

标签: ruby-on-rails

我正在创建一个包含标签的博客。使用Mongodb。 提交带有标签的新文章时出现此错误。并没有创造新的艺术。如果我没有在表单中添加任何标签,则会创建该文章。

ArticlesController中的NoMethodError #create 对于#

,未定义的方法“first”

Rails.root:c:/ Sites / blogK

应用程序跟踪|框架跟踪|完整追踪 app / models / article.rb:18:in all_tags=' app/controllers/articles_controller.rb:22:in new' app / controllers / articles_controller.rb:22:在'create'

article.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

_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 %>

0 个答案:

没有答案