我正在尝试建立一个用户可以预订房间的网站。我有一个工作中最喜欢的功能,但仅在用户登录时。如果访问者只想查看单个房间的show.html.erb,我会收到此错误:
我实际上已定义了收藏夹。
如何让访问者能够查看单个房间的show.html.erb?
rooms_controller.rb
before_action :set_room, only: [:show, :favorite]
...
...
def favorite
type = params[:type]
if type == "favorite"
current_user.favorites << @room unless current_user.favorites.exists?(@room)
redirect_to wishlist_path, notice: 'You favorited #{@room.listing_name}'
elsif type == "unfavorite"
current_user.favorites.delete(@room)
redirect_to wishlist_path, notice: 'Unfavorited #{@room.listing_name}'
else
# Type missing, nothing happens
redirect_to wishlist_path, notice: 'Nothing happened.'
end
end
private
def set_room
@room = Room.find(params[:id])
end
show.html.erb(会议室)
<% if current_user.favorites.exists?(@room) %>
<%= link_to "unfavorite", favorite_room_path(@room, type: "unfavorite"), method: :put %>
<% else %>
<%= link_to "favorite", favorite_room_path(@room, type: "favorite"), method: :put %>
<% end %>
我有一个用户,房间和favorite_room模型:
favorite_room.rb
belongs_to :room
belongs_to :user
user.rb
has_many :favorite_rooms # just the 'relationships'
has_many :favorites, through: :favorite_rooms, source: :room # the actual rooms a user favorites
room.rb
has_many :favorite_rooms # just the 'relationships'
has_many :favorited_by, through: :favorite_rooms, source: :user # the actual users favoriting a room
答案 0 :(得分:1)
您可以查看是否已定义current_user
试试这段代码
<% if current_user && current_user.favorites.exists(@room) %>
# your if
<% else %>
# your else
<% end %>