2014-10-13 1 views
0

처음에는 게시물을 만들 때 사용자 ID가 nil이었습니다. 원래 내 post_params는 단지 내용 : & : category. 내가 추가하기 전까지는 그렇지 않았습니다. user.id는 post.user.first_name이 제대로 작동하도록 할 수있었습니다. (first_name은 User 열입니다.) 게시물을 만들 때 한 지점에서 많은 실수를했습니다. id가 표시되지만 페이지를 새로 고침 할 때 ID가 사라집니다 (제출 후 게시물을 표시하기 위해 아약스를 사용하고 있습니다). 매개 변수에는 여전히 user_id가 포함되지 않지만 게시물이 만들어져 db에 저장되면 user_id가 있습니다. 나는 명시 적으로 user_id가 무엇인지 말하는 것이 아니므로 어떻게 알 수 있습니까? before_authentication에서! 필터를 작성 하시겠습니까? 또는 current_user.posts.create에서 ID를 가져 옵니까?레일스가 params 해시를 해석하는 방법, 엄격한 매개 변수

는 원래 다음

def create 
@post=post.create({content: post_params[:content], category: post_params[:category].downcase}) 
end 

...

def create 
@post = current_user.posts.create({content: post_params[:content], category: post_params[:category].downcase}) 
end 

private 

def post_params 
params.require(:post).permit(:content, :category, :user_id) 
end 


User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 6 ORDER BY "users"."id" ASC LIMIT 1 
(0.1ms) begin transaction 
SQL (0.3ms) INSERT INTO "posts" ("category", "content", "created_at", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?) [["category", "announcements"], ["content", "Hi All!"], ["created_at", "2014-10-13 19:58:02.937604"], ["updated_at", "2014-10-13 19:58:02.937604"], ["user_id", 6]] 
(3.8ms) commit transaction 
Like Exists (0.2ms) SELECT 1 AS one FROM "likes" WHERE "likes"."user_id" = 6 AND "likes"."post_id" = 69 LIMIT 1 
+0

조금 공부해야합니다. 'post_params'는 허용 된 매개 변수의 집합이며 그 자체로 사용됩니다. 'current_user.posts.create (post_params)'... 이렇게하면 DB 엔진에 전달 된 매개 변수가'def post_params'에 정의 된 매개 변수로 제한됩니다 ... –

답변

0

(이 경우 사용자의 게시물을) 만들거나 관계를 구축 호출하는 동안 자동으로 연결하는 좋은 관계 필드를 실체화 난간을했다 부모에게로의 오브젝트.

관련 문제