Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 204
Kenji Crosland Avatar asked Dec 22 '22 07:12

Kenji Crosland


1 Answers

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.

like image 128
Steve Graham Avatar answered Feb 06 '23 17:02

Steve Graham