3

基本上我想让一个链接能够从“收藏”动态刷新到“已删除”,同时让用户可以选择通过重新单击新按钮返回。该操作确实发生了,因为当我刷新页面时,更新的按钮会显示。为什么点击“收藏此课堂”链接不起作用?“删除此教室”链接似乎有效。谢谢你的帮助

收藏夹控制器.rb:

  def create
    current_classroom.add_to_favorites(@classroom)
    current_classroom.save
    respond_to do |format|
      format.js {  }
      format.html {redirect_to @classroom}
    end
  end

  def destroy
    current_classroom.remove_from_favorites(@classroom)
    current_classroom.save
    respond_to do |format|
      format.js {  }
      format.html {redirect_to @classroom}
    end
  end

收藏夹/create.js.erb

$("#favorite_classroom").html("<%= escape_javascript(link_to 'Remove the Classroom', classroom_favorite_path(@classroom), :remote => true, :method => :delete) %>");

教室/_classroom_details.html.erb

<div id="favorite_classroom">
<% if loggedin_user.favorite_classroom?(@classroom) %>
    <%= link_to 'Remove this Classroom', classroom_favorite_path(@classroom), :remote => true, :method => :delete %>
<% else %>
    <%= link_to 'Favorite this Classroom', classroom_favorites_path(@classroom), :remote => true, :method => :post %>
<% end %>

路线:

classroom_favorites POST   /classrooms/:classroom_id/favorites(.:format)  {:action=>"create", :controller=>"favorites"}
classroom_favorite DELETE /classrooms/:classroom_id/favorites/:id(.:format) {:action=>"destroy", :controller=>"favorites"}

单击“收藏此教室”链接时出错: ActionView::Template::Error (No route matches {:action=>"destroy", :controller=>"favorites"

谢谢!

4

3 回答 3

1

您在 js 文件中使用了两次双引号。你不能那样做。你需要像这样重写它 -

$("#favorite_classroom").html("<%= escape_javascript(link_to 'Remove the Classroom', classroom_favorite_path(@classroom), :remote => true, :method => :delete) %>");

现在请注意,Remove the Classroom 用单引号而不是双引号括起来。

此外,您的路线不正确,因为您在教室中嵌套了收藏夹。编写链接时,您需要添加要删除的 @favorite 对象:

= link_to 'Remove Favorite', classroom_favorite_path([@classroom, @favorite]), :remote => true, :method => :delete

现在您尝试访问的路线是有效的。那应该摆脱错误。

于 2012-08-14T20:54:56.570 回答
0

我认为您不需要最喜欢的控制器,您需要的是教室控制器的最喜欢/不喜欢的动作。这是它的外观

教室控制器.rb

respond_to :html, :js

def favorite
  # ... find classroom by id
  # do your stuff
  @classroom.favorite = !@classroom.favorite
  respond_with(@classroom)
end

意见/教室/favorite.js.erb

<%# the message should be oposite to favorite %>
<% msg = @classroom.favorite ? "Remove this Classroom" : "Favorite this Classroom" %>
$("#favorite_classroom").html("<%= escape_javascript(link_to msg, [:favorite, @classroom], :remote => true) %>");

这是路径助手的技巧,[:favorite, @classroom]应该翻译成/classrooms/:id/favorite. 如果它不起作用然后尝试favorite_classrooms_path(@classroom)

最后添加到您的routes.rb

resource :classrooms do 
  member { get :favorite }
end
于 2012-08-14T21:46:46.783 回答
0

看起来您需要在链接中引用“favorite_id”以匹配您的路线。

在您的情况下,可能是:

classroom_favorite_path([current_classroom, @classroom])
于 2012-09-18T01:20:20.900 回答