我正在尝试在Ruby on Rails应用程序中实现最喜欢的关系。路由,控制器和关系似乎都工作但link_to“收藏”不起作用,我的意思是它甚至没有生成html链接,虽然它没有抛出任何错误。我在这里关注这个例子Implement "Add to favorites" in Rails 3 & 4。
以下是代码:
的routes.rb
resources :locations do
put :favorite, on: :member
end
locations_controller.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
user.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
location.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 %>
答案 0 :(得分:1)
看起来您忘记了&lt; %%&gt;中的=,应该是:
<%= link_to "favorite", favorite_location_path(@location, type: "favorite"), method: :put %>