简体   繁体   中英

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 ? Because in my database I need to store for 1 game the user_id and the item_id. For now, I'm doing this which store only the user_id automatically :

 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 ?!


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. 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

  • retrieve every games from one item with something like 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

<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. Since I have no idea what your actual view looks like I am not sure where you are getting things like :time and :score

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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