2011-07-17 2 views
0

의 나는 그것을 약간 또한 설정 변경하려면 내가 PostsController레일 3 : 컨트롤러 내부의 방법을 만들 Post.new 대신 current_user.posts.build

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 => params [: post] [: user_id]. 나는 이것을 시도하고 있지만 current_user를 포함하지 않으므로 이들 메소드가 어떻게 다른지 궁금하다. 그리고 Post.new로 current_user.posts.build (params [: post])에 같은 기능을 유지하는 방법은 무엇인가? 게시물 모델 belongs_to에서

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 
+0

그냥 참고 사용자? 그렇지 않은 경우 user_id를 attr_accessible로 설정해야합니다. – Zabba

+0

죄송 합니다만 좀 더 자세히 설명해 드리겠습니다. 저는 프로그래밍과 레일에서 새로운 편이어서, 당신이 의미하는 바를 정확히 모르겠습니다. 나는 attr_accessible이 폼에서 대량 할당을 허용한다는 것을 이해합니다. 내 attr_accessible 아래에 user_id가 없습니다. 게시물 자체를 만든 사람의 user_id에 게시물의 user_id를 설정하려고합니다. 감사. –

답변

1

: 의도 한 목적에 따라, 당신은 사용자 ID가 막 누군가에 의해 할당되고 싶어하지 않을 수 있습니다

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 
+0

예, 관계 설정이 있습니다. @ post.user = current_user는 user_id => params [: post] [: user_id]와 동일합니까? 먼저 user_id를 설정해야합니다. –

+0

예. 그것을 시도하고 자신을 위해보십시오 – Uchenna

+0

도움을 주셔서 감사합니다. Post.new (params [: post]) 이후에 먼저 post의 user_id를 설정해야합니다. 위의 코드를 시도한 이유는 무엇입니까? @ post.update_attributes params [: post]는 두 번째로옵니다. –