Hi,
Trying to write a basic "blog-like" app in rails 3, I'm stuck with associations. I need the create method save the post_id as well as the user_id in the comment table (which I need in order to retrive all comments written by a user in order to display it)
The app has users (authentication - devise), posts (posted by users - but I'm not sure it matters in my case) and comments (on the posts, posted by users).
the comment table has a post_id, a body, and also a user_id
Associations:
has_many :comments (In the Post model)
belongs_to :post (In the Comment model)
belongs_to :user (In the Comment model)
has_many :comments (In the User model)
the routes:
resources :posts do
resources :comments
end
resources :users do
resources :comments
end
The comment post form displayed on the posts show view: (posts/show.html.erb)
<% form_for [@post, Comment.new] do |f| %>
<%= f.label :body %>
<%= f.text_area :body %>
<%= f.submit %>
<% end %>
and finally, the create method in the comments controller:
A.) If I write this a post_id is written in the database
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create!(params[:comment])
redirect_to @post
end
B.) If I write this a user_id is written...
def create
@user = current_user
@comment = @user.comments.create!(params[:comment])
redirect_to @post
end
I tried:
@comment = @post.comments.create!(params[:comment].merge(:user => current_user))
But it doesn't work.. How can I write a method which save the user_id and the post_id ? Did I have also to do some change in the comment post form (something like <% form_for [@post, @user, Comment.new] do |f| %> ?)
Thank you!