I have a user stored in a session which I would like to add as the owner of a comment. Rather than having a hidden field for user_id, I would like to add the user before the comment is saved in the controller.
What would be the best way to do this?
@comment = @post.comments.create(params[:comment])
Thanks.
There are a few strategies that work fairly well. You can have a call in the controller that staples the User on to the created comment:
Another way is to use something like model_helper (http://github.com/theworkinggroup/model_helper/) to provide access to controller properties within the model environment:
This method is more automatic, but at the price of transparency and possibly complicating your unit test environment.
A third approach is to merge in the parameters on the create call:
This has the disadvantage of not working very well if some of the properties of your model are protected, as they probably should be in any production environment.
Another trick is to create a class method that helps build things for you:
This is called on the relationship and will build in the correct scope: