MicropostsController中的NoMethodError #create

时间:2013-06-10 22:15:00

标签: ruby-on-rails ruby nomethoderror

我的Ruby on Rails应用程序遇到了问题。我有一个名为/ discussion的页面,其中包含用户可以使用微博评论的讨论。这里的目标是在每个微博下方都有一个表格,在提交时,将把文本放在讨论中。表单显示 - 但每当我点击提交时,我都会收到错误:

NoMethodError in MicropostsController#create

undefined method `micropost' for #<User:0x007f9744091680>
Rails.root: /home/nick/Documents/RailsProjects/buon

Application Trace | Framework Trace | Full Trace
app/controllers/microposts_controller.rb:8:in `create'

微博控制器

class MicropostsController < ApplicationController
  before_filter :signed_in_user, only: [:create, :destroy]

  def index
  end

  def create
    @micropost = current_user.micropost.build(params[:micropost])
     if @micropost.save
       flash[:success] = "Posted!"
       redirect_to root_url
     else
       render 'static_pages/home'
     end
  end

  def destroy
  end
end

_discusions.html

<% content_for :script do %>
<%= javascript_include_tag 'hover_content' %>
<% end %>

<li>
  <div class = "intro-bar"><span class = "intro"><%=discussion.intro %></span></div>
  <div class = "content-bar"><span class = "content"><%= discussion.content %></span></div>
  <span class = "timestamp">
    Posted <%= time_ago_in_words(discussion.created_at) %> ago.
  </span>
</li>
<% if signed_in? %>
<div class = "row">
  <aside class = "span4">
    <section>
      <%= render 'shared/micropost_form', :locals => {:discussion => discussion }%>
    </section>
  </aside>
</div>
<% end %>

微博模型

class Micropost < ActiveRecord::Base
  attr_accessible :break_votes, :content, :not_votes
  belongs_to :user
  belongs_to :discussion


  validates :content, presence: true, length: { maximum: 200 }
  validates :user_id, presence: true
  default_scope order: 'microposts.created_at DESC'
end

任何想法?

1 个答案:

答案 0 :(得分:0)

如果这是has_many关联,则需要复数,因此您的代码应为:

@micropost = current_user.microposts.build(params[:micropost])