在rails

时间:2015-08-30 07:55:30

标签: javascript jquery ruby-on-rails ajax ruby-on-rails-4

我想在我的rails应用中添加收藏夹功能。我为show.html.erb添加了部分收藏,它会显示最喜欢的链接或不喜欢的链接,如果我喜欢的文章,则不需要刷新整个页面:

#app/views/articles/show.html.erb
  <div class="panel-body"><p><%= markdown(@article.content) %></p></div>
  <div class="panel-footer" id="favorite">
  <div><%= render 'favorite_link' %></div>
...

_favorite_link.html.erb

<% if not Favorite.where(user_id: current_user.id, article_id: @article.id).first %>
  <%= link_to 'favorite', favorite_article_path(@article), {id: @article.id, method: :post}, remote: true %>
<% else %>
  <%= link_to 'unfavorite', unfavorite_article_path(@article), method: :delete, remote: true %>
<% end %>

favorite.js.erb

$("#favorite").html("<%= escape_javascript render partial: 'favorite_link' %>");

ArticlesController

def favorite
  @article = Article.find(params[:id])
  @article.favorites.create(user_id: current_user.id)
  render 'favorite'
end

def unfavorite
  @article = Article.find(params[:id])
  favorite = Favorite.where(user_id: current_user.id, article_id: @article.id).first
  favorite.destroy
  render 'favorite'
end

当我点击favorite link时,它不起作用,错误信息如下:

ActionView::MissingTemplate (Missing template articles/favorite, application/favorite with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in:
  * "/Users/liuxingqi/Public/Sparta/my_blog/mongo_project/app/views"
  * "/Users/liuxingqi/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/kaminari-0.16.3/app/views"
):
  app/controllers/articles_controller.rb:90:in `favorite' 

unfavorite效果很好。希望可以有人帮帮我!提前谢谢!

2 个答案:

答案 0 :(得分:0)

它搜索HTML扩展没有JS的视图,你有什么是favorite.js.erb,以确定对收藏的请求应该是ajax请求和格式:js类似

articles_favorite_path(format: :js)

答案 1 :(得分:0)

我找到了根本原因,因为错误的参数顺序,remote: true不起作用。

<%= link_to 'favorite', favorite_article_path(@article), {id: @article.id, method: :post}, remote: true %>

应该是:

<%= link_to 'favorite', favorite_article_path(@article), {id: @article.id, method: :post, remote: true} %>