0

我正在尝试在我的 Ruby on Rails 应用程序中实现最喜欢的关系。路由、控制器和关系似乎都在工作,但 link_to “收藏夹”不起作用,我的意思是它甚至没有生成 html 链接,尽管它没有抛出任何错误。我正在按照此处的示例在 Rails 3 和 4 中实现“添加到收藏夹”

这是代码:

路线.rb

resources :locations do
  put :favorite, on: :member
end

位置控制器.rb

class LocationsController < ApplicationController
  ....
  def favorite
    type = params[:type]
    if type == "favorite"
      current_user.favorites << @location
      redirect_to :back, notice: 'You favorited #{@location.name}'

    elsif type == "unfavorite"
      current_user.favorites.delete(@location)
      redirect_to :back, notice: 'Unfavorited #{@location.name}'

    else
      # Type missing, nothing happens
      redirect_to :back, notice: 'Nothing happened.'
    end
  end
end

用户.rb

 class User < ActiveRecord::Base
   ....
   # Favorite locations of user
   has_many :favorite_locations # just the 'relationships'
   has_many :favorites, through: :favorite_locations # the actual recipes a user favorites
   ....
 end

位置.rb

class Location < ActiveRecord::Base
  ....
  # Favorited by users
  has_many :favorite_locations # just the 'relationships'
  has_many :favorited_by, through: :favorite_locations, source: :user
end

查看/位置/show.html.erb

<% provide(:title, @location.name) %>

....
<% link_to "favorite", favorite_location_path(@location, type: "favorite"), method: :put %>
<% link_to "unfavorite", favorite_location_path(@location, type: "unfavorite"), method: :put %>
4

1 回答 1

1

看起来您忘记了 <% %> 中的 =,应该是:

<%= link_to "favorite", favorite_location_path(@location, type: "favorite"), method: :put %>
于 2013-06-30T04:26:26.430 回答