简体   繁体   English

Ruby on Rails属于许多人

[英]Ruby on Rails belongs_to many

Here is my situation : 这是我的情况:

Items : 项目:

has_many :games

Users : 用户数:

has_many :games

Games : 游戏:

belongs_to :user
belongs_to :item

On my Item page i have a link to create a new game. 在我的项目页面上,我有一个用于创建新游戏的链接。 How to get the item ID in a secure way ? 如何以安全的方式获取商品ID? Because in my database I need to store for 1 game the user_id and the item_id. 因为在我的数据库中,我需要为user_id和item_id存储1个游戏。 For now, I'm doing this which store only the user_id automatically : 现在,我正在这样做,它仅自动存储user_id:

 def create
    @game = current_user.games.build(game_params)
    if @game.save
      redirect_to root_url
    else
      render 'pages/home'
    end
  end

  private

    def game_params
      params.require(:game).permit(:time, :score)
    end

I suppose that adding a game_params :item_id is not the right way and is not secure ?! 我想添加game_params:item_id不是正确的方法,也不安全吗?


Here is the scenario wanted : 这是想要的方案:

A user came to an item page, click on a button to create a game, when I record the game I want to be able to store the user_id (it's OK for this part) and the item_id without any more user interaction. 用户来到项目页面,单击按钮以创建游戏,当我录制游戏时,我希望能够存储user_id(对于此部分来说是可以的)和item_id,而无需任何其他用户交互。 I don't want him to choose "manually" I want to "force it" (thanks to the item page where he comes from) 我不希望他“手动”选择我要“强制”(由于他来自何处)

In a perfect world I would like to : 在理想的世界中,我想:

  • retrieve every games from one user with something like current_user.games 使用current_user.games类的内容从一个用户检索每个游戏

  • retrieve every games from one item with something like item_id.games 使用item_id.games东西从一个物品中检索每个游戏

in your item page use: 在您的商品页面中使用:

new_form_path(item_id: @item.id)

instead of: 代替:

new_form_path

in your game form: 在您的游戏形式中:

= form_for @game do |f|
  = f.hidden_field :item_id, value: params[:item_id]

in your game controller: 在游戏控制器中:

params.require(:game).permit(:time, :score, :item_id)

There are many ways to do what you want, this is one of them. 有很多方法可以做您想要的,这就是其中一种。

I think this is what you are looking for 我想这就是你要找的

<%= button_to "New Game", {controller: 'games', action: 'create'}, params:{item_id: item.id} %>

this will generate html like 这将生成html之类的

<form method="post" action="/games/create" class="button_to">
    <div>
        <input type="hidden" name="item_id" value="YOUR ITEM ID" />
        <input type="submit" value="New Game" /> 
    </div>
</form>

When you click the button it will pass item_id as a post request to the controller. 当您单击按钮时,它将item_id作为发布请求传递给控制器​​。 Since I have no idea what your actual view looks like I am not sure where you are getting things like :time and :score 由于我不知道您的实际视图是什么样子,所以我不确定您在哪里得到诸如:time:score

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM