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.. H开发者_开发技巧ow 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!
To set up something very similar, I've used the following form:
<%= form_for [:place, @comment] do |f| %>
#form fields here
<%= end %>
Then in the comments controller:
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.build(params[:comment])
@comment.user = User.find(current_user.id)
respond_to do |format|
if @comment.save
format.html { redirect_to(@comment.post, :notice => 'Comment was successfully created.') }
else
format.html { render :action => "new" }
end
end
end
That should build the associations properly hopefully! Just as an aside, do you mean for comments to be nested under :users in your routes? If you just want to display all the user's comments on a profile page, you could do something like:
<p>
<b>Comments</b>
<% if @user.comments.empty? %>
No comments to display yet...
<% else %>
<% @user.comments.each do |comment| %>
<p>
<%= link_to "#{comment.post.title}", post_path(comment.post_id) %>, <%= comment.created_at %>
<%= simple_format comment.content %>
</p>
<% end %>
<% end %>
</p>
Hope some of that helps!
精彩评论