Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First you need to set up the database to handle this, personally I'd go with a has_many :through association because it provides more flexibility over has_and_belongs_to_many. The choice, however, is up to you. I recommend you look up the different types in the API and decide for yourself. This example will deal with has_many :through.</p> <p><strong>Models</strong></p> <pre><code># user.rb (model) has_many :favorites has_many :posts, :through =&gt; :favorites # post.rb (model) has_many :favorites has_many :users, :through =&gt; :favorites # favorite.rb (model) belongs_to :user belongs_to :post </code></pre> <p><strong>Controller</strong></p> <pre><code># favorites_controller.rb def create current_user.favorites.create(:post_id =&gt; params[:post_id]) render :layout =&gt; false end </code></pre> <p><strong>Routes</strong></p> <pre><code>match "favorites/:post_id" =&gt; "favorites#create", :as =&gt; :favorite </code></pre> <p><strong>jQuery</strong></p> <pre><code>$(".favorite").click(function() { var post_id = $(this).attr('id'); $.ajax({ type: "POST", url: 'favorites/' + post_id, success: function() { // change image or something } }) }) </code></pre> <p><strong>Notes</strong></p> <p>This assumes a couple of things: Using Rails 3, using jQuery, each favorite icon has an html id with the post id. Keep in mind I've not tested the code and I wrote it in this window so you probably have to fix some minor problems, but it should give you an impression of how <strong>I</strong> usually does this. The visual stuff and such I'll leave up to you.</p> <p>If anyone spot any mistakes please feel free to edit this post.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload