user6447029
user6447029

Reputation:

Rails: How do I prepopulate a text field in Rails?

I’m using Rails 4.2.3. I have this in my model …

class User < ActiveRecord::Base
  belongs_to :address

I have this in my controller

  def edit
    @user = current_user
    puts "address; #{@user.address} city: #{@user.address.city}"
    @default_country_selected = Country.find_by_iso('US')
  end

which prints out

address; #<Address:0x007f7f99a8d390> city: calgary

in my log. Then in my view corresponding to the above controller, I have

<%= form_for(@user) do |f| %>
    …
    <%= f.fields_for :address do |addr| %>
    <%= addr.label :address, "Home Town" %><br/>
    <div class="field"><%= addr.text_field :city, placeholder: "City", :class => 'textField' %></div>

which renders the text field as

<input placeholder="City" class="textField" type="text" name="user[address][city]" id="user_address_city" />

but as you can see, there is no “value” attribute rendered. How do I get the textfield pre-populated with the value of the address city? In this case< “calgary”?

Upvotes: 4

Views: 3884

Answers (1)

Fakhir Shad
Fakhir Shad

Reputation: 1101

That's very simple just assign the value like below and it will prepopulate it.

<%= addr.text_field :city, placeholder: "City", :class => 'textField' , value: @user.address.city %>

Upvotes: 6

Related Questions