Skip to content

Instantly share code, notes, and snippets.

@yohfee
Created June 17, 2014 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yohfee/07556e4c46da1819fc71 to your computer and use it in GitHub Desktop.
Save yohfee/07556e4c46da1819fc71 to your computer and use it in GitHub Desktop.
RE: Rails4 でお気に入りをオン・オフするトグルボタンみたいのをやってみるメモ
<% if current_user.fav? comment %>
<%= link_to "Favorite", comment_favorites_path(comment), method: :delete, remote: true, class: 'btn btn-xs btn-warning' %>
<% else %>
<%= link_to "Favorite", comment_favorites_path(comment), method: :post, remote: true, class: 'btn btn-xs btn-default' %>
<% end %>
$('#<%= dom_id @comment %>').html("<%=j render 'favorites/favorite_button', comment: @comment %>");
class FavoritesController < ApplicationController
before_action :set_comment
def create
current_user.favorites.create(comment: @comment)
end
def destroy
current_user.favorites.where(comment: @comment).destroy_all
render 'create'
end
private
def set_comment
@comment = Comment.find(params[:comment_id])
end
end
<h1>Listing comments</h1>
<table>
<tbody id="comments">
<% @comments.each do |comment| %>
<tr>
<td id="<%= dom_id comment %>">
<%= render 'favorites/favorite_button', comment: comment %>
</td>
</tr>
<% end %>
</tbody>
</table>
resources :comments do
resource :favorites, only: [:create, :destroy]
end
class User < ActiveRecord::Base
has_many :comments
has_many :favorites
def fav?(comment)
favorites.exists? comment: comment
end
end
@yohfee
Copy link
Author

yohfee commented Jun 17, 2014

http://d.hatena.ne.jp/CortYuming/20140617/p1

コメントに対してユーザのファボは一個だけだからresourceにするのもアリかもね解です
destroyが若干キモいけど!

@yohfee
Copy link
Author

yohfee commented Jun 17, 2014

gist並び順変わるの。。。

@yohfee
Copy link
Author

yohfee commented Jun 17, 2014

で、さらにやると例えば
resources :comments do
member { post :fav }
end
とかしてトグルするようにしたらもうちょいシンプルになるので
_人人人人_
> 宿題 <
 ̄Y^Y^Y ̄

@CortYuming
Copy link

あざーす
宿題やりますた
https://gist.github.com/CortYuming/88ccd49bc9b41e371dc0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment