2014-04-11 3 views
0

저는 루비 문서의 form_for를 통해 읽으려고 시도했지만 차이점을 이해하는 것은 여전히 ​​어렵습니다. @post와 : post의 차이점은 무엇입니까?

new.html.erb보기 :post 작품을로드

, 동안 @post하지 않습니다.

This is Post's new.html.erb 
<%= form_for(:post) do |f| %> 
    <%= f.text_area :note, value: "Say something" %><br> 
    <%= f.submit "Post" %> 
<% end %> 

PostController :

class PostsController < ApplicationController 
    before_action :signed_in_user, only: [:new, :create] 

    def index 
     @posts = Post.all 
    end 

    def new 
    end 

    def create 
     @post = current_user.posts.build 
     puts "This is #{@post.user_id} user" 
     redirect_to posts_path if @post.save #post/index.html.erb 
    end 

    def destroy 
    end 

    private 

    def signed_in_user 
     redirect_to signout_path, notice: "Please sign in." unless signed_in? 
    end 
end 
+0

guides.rubyonrails.org를 사용해 보셨습니까? –

+3

가능한 복제본 http://stackoverflow.com/questions/957204/instance-variable-vs-symbol-in-ruby-on-rails-form-for –

+0

예, 명확하지 않았습니다. – funfuntime

답변

2

:post은 "나에게 새로운 포스트 객체를 만들고 그것으로 형태를 구축"하는 레일 번역 얻을 것이다 다음은 관련 뷰와 컨트롤러입니다. @post 먼저 컨트롤러 액션에서이를 초기화 할 필요가 는 자주 연관된 객체를 구축, 설정 값 (양식을 렌더링하기 전에 몇 가지 초기화 작업을 수행하고자 끝날 것 때문에

def new 
    @post = Post.new 
end 

당신은 오히려 @post를 사용해야 즉, 사용 등)

당신이 사용자와 포스트를 연결하려는 경우 (사용 CURRENT_USER는) 당신이 그것을 할 수있는 여러 가지 방법

  1. @ post.user_id = current_user.id
  2. @ post.user = 사실
  3. @post = current_user.posts.build (PARAMS ...)

CURRENT_USER, 세 번째 방법은이를위한 가장 좋은 방법이다.

또한 만든/업데이트 작업에서 생성 된 개체를 current_user와 연결해야하므로 사용자가 양식을 보낸 후 항상 기억해야합니다. 양식 필드로 user_id를두면 분명히 사용자가 변경할 수 있습니다!

+0

후속 질문으로'@ post'와'user_id'의 foreign_key를 어떻게 설정할 수 있습니까? '@post.user_id = current_user.id'가 될까요? – funfuntime

+1

예, 정확하게. 액션을 생성 할 때만 그것을 수행해야하므로 사용자는 가치를 조작 할 수 없습니다. 내 업데이트 답변을 참조하십시오. –

관련 문제