Helper方法未触发



我正在开发一个应用程序,您可以在其中向库中添加游戏,也可以删除它们。我有通过点击按钮工作的添加功能,然而我的if语句会弹出";从库中删除";没有显示。

这是我的游戏控制器中控制添加/删除功能的库方法:

def library
type = params[:type]
game = Game.new(game_params)
game.fetch_data
if type == "add"
current_user.library_additions << game
redirect_to user_library_path(current_user), notice: "Game was added to your library"
elsif type == "remove"
current_user.library_additions.delete(game)
redirect_to root_path, notice: "Game was removed from your library"
else
# Type missing, nothing happens
redirect_to game_path(game), notice: "Looks like nothing happened. Try once more!"
end

在视图中;添加到库";按钮应该出现在不在库中的游戏上,如果它在库中,它应该切换到";从库中删除";

<% if user_added_to_library?(current_user, game) %>
<button type="button"><%= link_to 'Remove from library', add_game_path(game.id, type: "remove", game: game), method: :put %> </button>
<% else %>
<button type="button"> <%= link_to 'Add to library', add_game_path(game.id, type: "add", game: game), method: :put %> </button>
<% end %>

由user_added_to_library确定的操作?不起作用,所以我总是看到"添加到库"按钮。

这是我的user_added_to_library助手吗?

module GamesHelper
def user_added_to_library? user, game
user.libraries.where(user: user, game: @game).any?
end
end

我想也许我需要将库更改为library_addments,但我得到StatementInvalid错误。现在编写代码的方式不会出现错误,但它可能根本不存在。

我的用户模型(如果有必要(:

class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :games
has_many :libraries
has_many :library_additions, through: :libraries, source: :game
end

我需要更改我的user_added_to_library吗?方法还是存在其他问题?

这里的大象实际上是这个代码的一组总体设计问题。这种设计与RESTful相去甚远,并且违反了HTTP谓词的语义(PUT不应该删除资源(,并且只有一个方法来完成许多不同的工作(创建和销毁资源(真的很糟糕。你甚至没有检查游戏是否真的保存了。

销毁资源应该使用DELETE请求完成。在Rails中,只需正确使用HTTP谓词即可创建和修改资源:

POST    /games      # create a game
PATCH   /games/:id  # update a game
DELETE  /games/:id  # destroy a game

大多数情况都可以而且应该由resources宏生成的标准CRUD路由来处理。如果您有具有关系的资源,则可以使用嵌套路由来描述这些关系。在这种情况下,您可能会选择将路线嵌套在单一资源中,因为您正在向当前用户添加/删除游戏。

# generates 
# POST     /user/games
# DELELE   /user/games/:id
resource :user, only: [] do
resources :games, only: [:create, :destroy]
end 

这将由GamesController中的#create#destroy方法处理。

第二个问题实际上是数据库的设计和模型。如果你想创建一个用户可以将游戏组织到不同库中的设计,你可以通过:

class User < ApplicationRecord
has_many :libraries
has_many :games, through: :libraries
end
class Library < ApplicationRecord
belongs_to :user
has_many :library_games
has_many :games, through: :library_games
end 
class LibraryGame < ApplicationRecord
belongs_to :library
belongs_to :game
has_one :user, through: :library 
end
class Game < ApplicationRecord
has_many :library_games
has_many :libraries, through: :library_games
has_many :users, through: :libraries
end

在树上设置间接关联可以通过以下方式检查用户是否有游戏:

class User < ApplicationRecord
has_many :libraries
has_many :games, through: :libraries
def has_game?(game)
games.where(id: game.id).exist?
end 
end

实际上,根本没有理由需要一个helper方法。毕竟,你实际上只是在问用户对象一个问题。这不应该涉及将两个不同的对象传递给一个单独的方法。

最新更新