What is the difference between using ":" and "@" in fields_for

I am setting up inline forms in my rails application.

This does not work

<h1>PlayersToTeams#edit</h1>
<%= form_for @players_to_teams do |field| %>
  <%= field.fields_for @players_to_teams.player do |f| %>
    <%= f.label :IsActive %>
    <%= f.text_field :IsActive %>
  <% end %>
  <%= field.label :BT %>
  <%= field.text_field :BT %>
  <br/>
  <%= field.submit "Save", class: 'btn btn-primary' %>
<% end %> 

Gives me a mistake ActiveRecord::AssociationTypeMismatch. Pay attention to @players_to_teams.playerthe line forms_for.

It works:

<h1>PlayersToTeams#edit</h1>
<%= form_for @players_to_teams do |field| %>
    <%= field.fields_for :player do |f| %>
        <%= f.label :IsActive %>
        <%= f.text_field :IsActive %>
    <% end %>
    <%= field.label :BT %>
    <%= field.text_field :BT %>
    <br/>
    <%= field.submit "Save", class: 'btn btn-primary' %>
<% end %>

Notice the call :playerin line fields_for.

What is the difference between using a character and using an instance? I would think I would like to use an instance in this case, but I don’t think?

Edit

models:

class Player < ActiveRecord::Base
  has_many :players_to_teams
  has_many :teams, through: :players_to_teams
end

class PlayersToTeam < ActiveRecord::Base
  belongs_to :player
  belongs_to :team

  accepts_nested_attributes_for :player
end

controller:

class PlayersToTeamsController < ApplicationController
  def edit
    @players_to_teams=PlayersToTeam.find(params[:id])
  end

  def update
    @players_to_teams=PlayersToTeam.find(params[:id])
    respond_to do |format|
      if @players_to_teams.update_attributes(params[:players_to_team])
        format.html { redirect_to @players_to_teams, notice: 'Player_to_Team was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @players_to_teams.errors, status: :unprocessable_entity }
      end
    end
  end
end

Project example

Github: https://github.com/workmaster2n/embedded-form-errors

+4
source share
1 answer

, fields_for , player @players_to_teams. (.. :player). ? :.

class PlayersToTeam < ActiveRecord::Base
  has_one :player
end

class Player < ActiveRecord::Base
  belongs_to :players_to_team
end

, fields_for, record_name, , Rails , . , , , fields_for.


, . , , .

accepts_nested_attributes_for player_attributes=. player=, has_one. player_attributes= , player= player.

, fields_for @players_to_teams.player:

<input name="players_to_team[player][name]" ... />

fields_for :player:

<input name="players_to_team[player_attributes][name]" ... />

update_attributes player=, player_attributes=. , , ( params ).

AssociationTypeMismatch: player=, player.

, fields_for accepts_nested_attributes_for , .

, , , , , : -)

+5

All Articles