Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails创建包含来自不同表的两个外键的模型_Ruby On Rails_Postgresql_Model - Fatal编程技术网

Ruby on rails Rails创建包含来自不同表的两个外键的模型

Ruby on rails Rails创建包含来自不同表的两个外键的模型,ruby-on-rails,postgresql,model,Ruby On Rails,Postgresql,Model,我有两种型号:User和Game。我需要从这些模型中创建包含fk的模型(game\u id和user\u id)。这意味着用户可以玩多个游戏。 我生成了这个模型: class CreateUserGames < ActiveRecord::Migration[5.1] def change create_table :user_games do |t| t.references :game, foreign_key: true t.references

我有两种型号:
User
Game
。我需要从这些模型中创建包含fk的模型(
game\u id
user\u id
)。这意味着
用户
可以玩多个游戏。 我生成了这个模型:

class CreateUserGames < ActiveRecord::Migration[5.1]
  def change
    create_table :user_games do |t|
      t.references :game, foreign_key: true
      t.references :user, foreign_key: true
      t.timestamps
    end
  end
end
class CreateUserGames
所以,主要的问题是,我需要添加按钮“Take”(或类似的smth),如果用户登录,它会在这个表中创建一条记录,其中包含当前游戏的id和当前用户的id。
现在我该怎么办?

您可以将链接与post方法一起使用,并创建一个操作来处理该问题。例如:

link_to "Take", 'your_action_url', method: post, game_id: 'your_game_id'
另外,请记住在
route.rb上创建操作url:

  match "your_action_url" => "your_controller#take_game", via: [:post]
然后,您可以使用以下内容创建您的操作:

def take_game
   user_id = current_user.id #(if you're using devise)
   if UserGame.create!(game_id: params[:game_id], user_id: user_id)
     #handle success and return to the view
   else
     #handle error
   end
end

我想这是个好办法。希望这有帮助

嘿!非常感谢,伙计!这绝对是我需要的!不幸的是,我没有足够的声誉来感谢你