views:

42

answers:

1

Hello, I have a comments table which includes a column for user_id

I have the follow in my comments controller

  def create
    @commentable= context_object()
    @comment = @commentable.comments.build(params[:comment])
  .
  .

Problem is this doesn't pass the current_user's user_id. How can I update the above to be something like current_user.comments.build....

Thanks

+1  A: 

The easiest would be to just do:

@comment.user = current_user

You should be able to do this too:

current_user.comments << @comment
captaintokyo
tried that, didn't work, still inserted as NULL. Also, don't I want it to be something like current_user.comments.build ..... so that I don't have to make the user_id column attr accessible in the comments model?
AnApprentice
I think in the solution I suggest `user_id` needs to be accessible. If it's not accessible it would explain why you still get `NULL` in your `user_id` column. `context_object()` doesn't seem to be a standard rails3 function. Can you explain what it does?
captaintokyo
Thanks CaptainT, I'm implementing commenting, take a look at the private function here: http://github.com/rbritom/Simple_polymorphic_nested_comments/blob/master/app/controllers/comments_controller.rb What do you think?
AnApprentice
Also, what does the << do? I haven't seen that before, and according to google it's an operator that shifts left?
AnApprentice
`<<` adds the newly created comment to a collection of existing comments. In this case it adds the new comment to the the collection of `current_user`'s previous comments.
captaintokyo
@TheApprentice: I updated my answer. Just add the created comment to the `current_user` using `<<`.
captaintokyo
I tried the "current_user.comments << @comment" and that errored with "ActiveRecord::AssociationTypeMismatch (Comment(#2174387700) expected, got NilClass(#2148254600)): app/controllers/comments_controller.rb:28:in `create'" But got this working, what do you think? "@comment = @commentable.comments.build(params[:comment].merge(:user_id => current_user.id))"
AnApprentice
Yeah, that's fine too. Maybe you should add your answer and accept it, so other people know what worked for you.
captaintokyo