ruby-on-rails - 未定义的方法 `microposts'

标签 ruby-on-rails ruby ruby-on-rails-3

以前可以,为什么现在不行了?我试图仅由登录用户创建帖子。还是我的路由问题? 我的路由是 资源:用户做 资源:微博 结束

微博 Controller

def create
    @micropost = current_user.microposts.build(params[:micropost])
    if @micropost.save 
        flash[:success] = "Post created!"
        redirect_to @micropost
    else
        render 'new'
    end
end

new.html.erb

 <%= form_for @micropost do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<%= f.hidden_field :user_id, :value => current_user.id %>

<%= f.label :title %><br />
<%=h f.text_field :title %><br />

<%= f.label :content %><br />
<%=h f.text_area :content, :row => 30, :cols=> 30 %><br />

<%= f.label :category %><br />
<%=h f.text_field :category %><br />

<%= f.submit "Post" %>

微博模型

class Micropost < ActiveRecord::Base
belongs_to :users
default_scope :order => 'microposts.created_at DESC'

attr_accessible :title,:content,:category

validates :user_id, :presence => true
validates :title,    :presence => true,
                     :length => {:maximum =>500}                            
validates :content,  :presence => true,
                     :length => {:maximum =>3000}                           
validates :category, :presence => true

end

迁移微博

class CreateMicroposts < ActiveRecord::Migration
  def self.up
create_table :microposts do |t|
  t.string :title
  t.string :content
  t.string :user_id
  t.string :category

  t.timestamps
end
    add_index :microposts, [:title, :created_at, :category]
  end

  def self.down
    drop_table :microposts
 end
end

最佳答案

您的用户模型需要:

has_many :microposts

关于ruby-on-rails - 未定义的方法 `microposts',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8116176/

相关文章:

ruby-on-rails - 将 Rails 应用程序与 Google Apps 集成

c - 在 C 中运行 Ruby

ruby-on-rails-3 - 为什么我无法阻止 Solr 运行?

ruby-on-rails - rails : How to determine controller/action in view

ruby - 尽管未定义操作和路由,但 RSpec 成功

ruby-on-rails - Capistrano 部署和 schema.rb

mysql - PG 缺少表的 FROM 子句条目

ruby-on-rails - Rails 3.1 Asset Pipeline 对我不起作用

ruby-on-rails - 找不到 gem 'sqlite3 (>= 0) ruby'

ruby - 轨道安全 : converting parameters to symbols for hash lookup