本文介绍了未定义的方法`microposts'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以前可以,但为什么现在不行了?我试图仅由登录用户创建帖子.还是我的路由问题?我的路由是资源:用户做资源:微博结束
It worked before but why it isn't now? I was trying to to create a post by only the signIn user.Or is it my routing problems?My routing isresources :users doresources :micropostsend
微博控制器
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
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
这篇关于未定义的方法`microposts'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!