Rails 3:在控制器内创建方法,Post.new 而不是 current_user.posts.build
我将此作为 PostsController 中的创建方法,
class PostsController < ApplicationController
def create
@user = current_user
@post = current_user.posts.build(params[:post])
if @post.save
flash[:success] = "Post created!"
redirect_to root_path
else
@feed_items = current_user.feed.paginate(:per_page => "10", :page => params[:page])
render 'pages/home'
end
end
我想稍微更改一下以设置 :user_id =>参数[:post][:user_id]。我正在尝试这个,但它不包括 current_user 所以我想知道这些创建方法有何不同,以及如何在 current_user.posts.build(params[:post]) 和 Post.new 中保持相同的功能?
def create
@post = Post.new :user_id => params[:post][:user_id]
@post.update_attributes params[:post]
if @post.save
flash[:success] = "Post created!"
redirect_to root_path
else
@feed_items = current_user.feed.paginate(:per_page => "10", :page => params[:page])
render 'pages/home'
end
end
end
I have this as my create method inside my PostsController
class PostsController < ApplicationController
def create
@user = current_user
@post = current_user.posts.build(params[:post])
if @post.save
flash[:success] = "Post created!"
redirect_to root_path
else
@feed_items = current_user.feed.paginate(:per_page => "10", :page => params[:page])
render 'pages/home'
end
end
I'd like to change it slightly to also set :user_id => params[:post][:user_id]. I'm trying this but it doesn't include the current_user so I am wondering how are these create methods different and how would I keep the same functionality in current_user.posts.build(params[:post]) with Post.new ?
def create
@post = Post.new :user_id => params[:post][:user_id]
@post.update_attributes params[:post]
if @post.save
flash[:success] = "Post created!"
redirect_to root_path
else
@feed_items = current_user.feed.paginate(:per_page => "10", :page => params[:page])
render 'pages/home'
end
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在你的帖子模型中belongs_to:user
in your post model belongs_to :user