Kenji Crosland
Kenji Crosland

Reputation: 3034

Automatically fill in form fields in Rails?

Lets say you had a simple form to create a new article object in your application.

<% form_for @article do |f| %>
<p>
  name:<br />
  <%= f.text_field :name  %>
</p>
<p>
  link:<br />
  <%= f.text_field :link %>
</p>

<p>
  <%= submit_tag %>
</p>

I'm using the RSS feed parser Feedtools to get the article names but I can't seem to automatically fill in the form fields from data that is accessible elsewhere. Say the name of the article is accessible through params[:name]. How could I get the name of the article from params[:name] (or params[:link] for that matter) into the form field without the user having to type it in? I don't want to automatically create an article object either because the user may want to modify the name slightly.

Upvotes: 4

Views: 11060

Answers (1)

Steve Graham
Steve Graham

Reputation: 3021

If you pass the information you want to display to the Article constructor in the new action, the form will render populated. Even though a new object has been instantiated, it will not be persisted to the db because at no point has the save method been called on it. That will happen in the create action.

def new
  @article = Article.new :name => "Steve Graham's insane blog", :link => "http://swaggadocio.com/"

  respond_to do |format|
    format.html # new.html.erb
    format.xml  { render :xml => @post }
  end
end

Without knowing more about your app logic, I can't offer anymore help on how to stitch the parts together. This should get you nearly there though.

Upvotes: 11

Related Questions