I have just started learning Rails and I’m trying to build a post/like type feature. I have got it working but there must be a more a efficient way of doing it.
My post index view contains the following code (I’m using jQuery to submit the form via ajax):
<% @posts.each do |post| %>
<%= form_for([post, post.likes.build]) do |f| %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<%= f.hidden_field :post_id, :value => post.id %>
<%= f.submit pluralize(post.likes.count, 'Like'), :class => 'like like-' + post.id.to_s %>
<% end %>
<% end %>
My show view contains the following:
<%= render "likes/form" %>
Which contains the following:
<%= form_for([@post, @post.likes.build]) do |f| %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<%= f.hidden_field :post_id, :value => @post.id %>
<%= f.submit pluralize(@post.likes.count, 'Like'), :class => 'like like-' + @post.id.to_s %>
<% end %>
This all works combined with jQuery and destroy links. However having two different forms seems a bit heavy duty. Any ideas on how to change/optimize or the best way of doing this?
Thanks.
Edit form.html.erb your form partial