我实现了一个功能,用户将笑话标记为收藏夹。因为我已经在使用acts_as_votable进行upvoting / downvoting,并希望与用户赞成不同,所以我自己构建了它。
现在,用户通过点击“收藏”链接或“不喜欢”链接来创建收藏。这并不理想,因为用户可以通过这种方式创建重复的收藏夹。
我更愿意将其更改为切换,我首先检查用户是否将笑话标记为收藏夹,然后根据该状态显示相应的操作。我不知道怎么回事。有人能指出我正确的方向吗?
我的笑话控制器:
# Add and remove favorite jokes
# for current_user
def favorite
@joke = Joke.find(params[:id])
type = params[:type]
if type == "favorite"
current_user.favorites << @joke
redirect_to :back, notice: 'Added to favorites'
elsif type == "unfavorite"
current_user.favorites.delete(@joke)
redirect_to :back, notice: 'Removed from favorites'
else
# Type missing, nothing happens
redirect_to :back, notice: 'Nothing happened.'
end
end
我的模特: (笑话)
has_many :favorite_jokes
has_many :favorited_by, through: :favorite_jokes, source: :user
(Favorite_Joke)
belongs_to :joke
belongs_to :user
(用户)
has_many :favorite_jokes
has_many :favorites, through: :favorite_jokes, source: :joke
我的观点:
<div class="col-sm-4 col-xs-12 text-center">
<button type="button" class="btn btn-danger btn-block">
<i class="fa fa-heart"></i>
<span class="badge">favorite</span>
</button>
</div>
<% if current_user %>
<%= link_to "favorite", favorite_joke_path(@joke, type: "favorite"), method: :put %>
<%= link_to "unfavorite", favorite_joke_path(@joke, type: "unfavorite"), method: :put %>
<% end %>
最后,我的路线:
resources :jokes do
member do
put "like" => "jokes#upvote"
put "unlike" => "jokes#downvote"
end
put :favorite, on: :member
end
答案 0 :(得分:0)
一个选项是检查呈现该视图的动作(看起来像是jokes_controller #show),如果current_user在该特定笑话的favorite_jokes表中有一行。
在jokes_controller中#show action:
$scope.showDetails = function(name){
$rootScope.name=name;
//your code
}
然后在视图中,例如:
@favorited = FavoriteJoke.find_by(user: current_user, joke: @joke).present?
然后在你的<% if @favorited %>
<%= link_to "unfavorite", unfavorite_joke_path(@joke), method: :put %>
<% else %>
<%= link_to "favorite", favorite_joke_path(@joke), method: :put %>
<% end %>
文件中,创建一个既有利益又无利可图的路径,而不是在一个动作中执行该逻辑。