简体   繁体   English

为什么我不能使用参数创建 object?

[英]Why i can't create object with params?

I've been suffering from a problem for several days.几天来我一直在为一个问题而烦恼。 I can not create an object using the parameters from the form.我无法使用表单中的参数创建 object。 My form:我的表格:

<%= form_with(model: @battle, local: true) do |form| %>
<div class="field">
  <%= form.collection_select(:team_id, @teams, :id, :name) %>
</div>
  <%= form.submit 'Submit'%>
<% end %>

In this form i want to choose only 1 team.在这种形式中,我只想选择 1 个团队。

controller: controller:

  def create
    @battle = Battle.new
    @battle.user_id = current_user.id
    @battle.team_ids = params[:team_id]
    if @battle.save
      redirect_to root_path, notice: "Battle has been created"
    else
      render :new
    end
  end

  def battle_params
    params.require(:battle).permit(:team_id)
  end

And when used, this form creates an object without reference to the team.使用时,此表单会创建一个 object,而无需参考团队。

logs:日志:

Processing by BattlesController#create as HTML
  Parameters: {"authenticity_token"=>"0wWoFrQXYkEsXsMRgGyKi5Mde7WndhI6zYWY4KvhQlgdcCAaCZqH1z1z9dK0x91iqOPw/Jsb2T6Q+EVtGz4VsA==", "battle"=>{"team_id"=>"14"}, "commit"=>"Submit"}
  User Load (0.7ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/battles_controller.rb:14:in `create'
  Team Load (0.4ms)  SELECT "teams".* FROM "teams" WHERE 1=0
  ↳ app/controllers/battles_controller.rb:15:in `create'
   (0.4ms)  BEGIN
  ↳ app/controllers/battles_controller.rb:16:in `create'
  User Load (0.5ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/battles_controller.rb:16:in `create'
  Battle Create (3.8ms)  INSERT INTO "battles" ("user_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["user_id", 1], ["created_at", "2020-06-19 10:28:28.036147"], ["updated_at", "2020-06-19 10:28:28.036147"]]

If I try to create a battle with two teams, but it will be created with only one (without using parameters):如果我尝试与两个团队创建一场战斗,但它将只创建一个(不使用参数):

@battle.team_ids = [params[:team_id], 14]

Although, a battle is created without problems in the console:虽然,在控制台中创建了一场没有问题的战斗:

battle = Battle.new
battle.team_ids = [13, 14]

I don't understand what the problem may be.我不明白问题可能是什么。

Instead of params[:team_id] try using battle_params[:team_id] instead:代替params[:team_id]尝试使用battle_params[:team_id]代替:

@battle.team_ids = battle_params[:team_id]

otherwise you'd need to call params[:battle][:team_id] which is not the Rails way as it isn't as secure, but it would still work.否则你需要调用params[:battle][:team_id]这不是 Rails 的方式,因为它不安全,但它仍然可以工作。

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

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