将随机ID号放在create上的关联表中

时间:2012-05-28 13:35:29

标签: ruby-on-rails ruby ruby-on-rails-3.1

我正在尝试在我的关联表中放置一个随机ID号。我该怎么办?

def create
  @rand = rand(1...10)
  @player = Player.new(params[:player])
  @player.result_id = @rand
  if @player.save
    render :action => "new"
  else
    render :action => "new"
  end        
end

1 个答案:

答案 0 :(得分:1)

只需选择一个随机结果ID:

@player.result_id = Result.offset(rand(Result.count)).select('id').first.id

选择随机记录,请参阅 Rails 3: Get Random Record