At first, when I was creating posts, the user id was nil. Originally my post_params were just :content & :category. It wasn't until I added :user_id that I was finally able to get post.user.first_name to work properly.(first_name is a User column) I screwed around a lot with it and at one point when I was creating posts, the id would show up, but then on a refresh of the page, the id would disappear(I am using ajax to show the post after submit). The params still do not include :user_id, but now when the post is created and put into the db, the user_id is there. I am not explicitly saying what the user_id is, so how does it know? from the before_authentication! filter from devise? Or does it get the id from current_user.posts.create?
Originally had
def create
@post=post.create({content: post_params[:content], category: post_params[:category].downcase})
end
then...
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
post_params
is a set of permitted parameters and is used as such.current_user.posts.create(post_params)
... This will limit the parameters submitted to the DB Engines to the ones defined indef post_params
and those alone...