views:

376

answers:

2

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.

+1  A: 

Setting the value of an input field is easy and can be done like this,

<%= f.text_field :name, :value => params[:name]  %>

Depending on your params hash has you may need to furthur specify which array value you want, for example if your parameter hash look similar to the following,

Parameters: {"feed_data"=>{"name"=>"Super Feed", "link"=>"link to feed"}

<%= f.text_field :name, :value => params[:feed_data][:name]  %>

<%= f.text_field :link, value => params[:feed_data][:link] %>
Joey
This works! Thanks a lot!
Kenji Crosland
You shouldn't be using params in your views. Assign to an instance variable in your controller. Also you're repeating yourself by setting the value manually for each form element.
Steve Graham
+3  A: 

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.

Steve Graham
Thanks Steve. This one should work too.
Kenji Crosland
no probs kenji!
Steve Graham
I'd venture this is the more "standard" way of doing it, since you are using an @article object this lets you reuse the form partial for new and edit.
MattMcKnight