Ruby on rails Rails 3:在控制器内创建方法,Post.new而不是当前的_user.posts.build

Ruby on rails Rails 3:在控制器内创建方法,Post.new而不是当前的_user.posts.build,ruby-on-rails,ruby-on-rails-3,methods,controller,Ruby On Rails,Ruby On Rails 3,Methods,Controller,我将此作为PostsController中的create方法 class PostsController < ApplicationController def create @user = current_user @post = current_user.posts.build(params[:post]) if @post.save flash[:success] = "Post created!"

我将此作为PostsController中的create方法

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

def create
  @post = Post.new(params[:post])
  @post.user = current_user
  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

请注意:根据您的预期用途,您可能不希望任何人都可以分配用户id?如果不是,那么你应该让用户id attr\u可访问。很抱歉,你能再详细说明一下吗?我对编程和rails不太熟悉,所以我不太清楚你的意思。我知道attr_accessible允许从表单进行批量分配。我现在无法访问属性下的用户id。我希望将帖子的user\u id设置为创建帖子的人的user\u id。谢谢。是的,我确实建立了这种关系。@post.user=当前用户是否与:user\u id=>params[:post][:user\u id]执行相同的操作?我需要先设置用户id。谢谢您的帮助。我需要先设置帖子的用户id,而不是在post.new(params[:post])之后,这就是为什么我尝试上面的代码,其中@post.update_attributes params[:post]排在第二位
def create
  @post = Post.new(params[:post])
  @post.user = current_user
  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