【发布时间】:2017-10-24 19:15:24
【问题描述】:
我的 Rails 应用程序中有一个表单,用户只需输入一个数字,然后使用 ajax 提交表单。如果所有参数都存在,则会在我的游戏控制器中创建一个新游戏。我有两个 hidden_field_tags,它们的参数很好地传递给控制器,但最重要的参数,即从用户输入获得的参数,似乎没有传递给控制器。
我的表格:
<%= form_for @game, :url => {:controller => "games", :action => "create" }, :html => { :role => 'form' }, remote: true, method: :post do |f| %>
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="input-group">
<%= f.text_field :user_stake, class: 'form-control' %>
<span class="input-group-btn">
<%= f.submit 'Go', :html => { :type => "button" }, class: "btn btn-default" %>
</span>
</div>
</div>
</div>
<%= hidden_field_tag 'user_id', current_user.id %>
<%= hidden_field_tag 'jackpot_id', @jackpot.id %>
<% end %>
控制器:
before_action :game_params, only: [:create]
def create
@game = Game.new(game_params)
if @game.save
@jackpot = Jackpot.find(params[:jackpot_id])
ActionCable.server.broadcast 'jackpot_channel',
users: Jackpot.where(id: @jackpot.id),
pot: @jackpot,
user: User.find(@game.user_id),
game: @game,
stake: @game.user_stake.to_s
else
ActionCable.server.broadcast 'jackpot_channel',
error: @game.errors.full_messages
end
end
def new
@game = Game.new
end
private
def game_params
params.permit(:user_stake, :user_id, :jackpot_id)
end
无论在@game 中输入什么,都会以 0.0 的 user_stake 保存,我已在迁移中将其设置为默认值。我不知道我在这里做错了什么。有任何想法吗?谢谢!
【问题讨论】:
-
Rails 服务器中是否有提示提交表单?
-
删除
before_action :game_params, only: [:create]。除了浪费时间/内存之外,它绝对没有任何作用。 -
什么是 DB 列类型?
-
@max 是小数
标签: ruby-on-rails model-view-controller parameters actioncable