Reputation: 199
I’ve been suffering from a problem for several days. I can not create an object using the parameters from the form. 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.
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.
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.
Upvotes: 0
Views: 66
Reputation: 86
Instead of params[:team_id]
try using battle_params[:team_id]
instead:
@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.
Upvotes: 1