views:

78

answers:

2

This might be a really basic question but how do I create default values in forms?

I'm trying to put the <%= params[:id] %> of the page in as a default hidden value in this form.

`<% form_for(@revision) do |f| %> <%= f.error_messages %>

<%= f.label :background_title %><br />
<%= f.text_field :background_title %><%= params[:id] %>

<%= f.label :title %><br />
<%= f.text_field :title %>

<%= f.submit 'Create' %>

<% end %>`

Thanks.

A: 

The form is linked to the object you pass to form_for, so set the value on the object before you start the form. For example, in the controller:

@revision.id = params[:id]

then in the form:

<%= f.hidden_field :id %>

However, I hope this is an example and you're not actually setting the ID (primary key) of an object based on a URL parameter...

Alex Reisner
I tried this and it's still not working. but yes, I'm setting the id based on a url parameter. is that bad?
actually, it's now working. But I'm still concerned about your comment, why is it bad that the ID is based on a url?
One reason is that anyone could pass whatever they wanted in there, just by throwing some # in the url. Even better, they could throw a gigantic # in and potentially have your app cough up some blood.
theIV
Except in rare cases you should not be supplying an ID for new objects, but rather leaving the ID attribute nil and letting the DB assign the next available integer automatically. Otherwise you risk security problems (as mentioned by theIV), duplicate ID problems, and more.
Alex Reisner
Thanks guys, this creates a bigger problem though. I'm creating a twitter application where @mentions automatically link to app.com/tags/mentions . I want anything (that's not malicious code or over 140 characters) to be able to have a tag.how would I get around this?
Hmmm...what you're doing sounds fine. This may be a misunderstanding about how you're using the ID. I don't know how your application works, but if you have a comment form at the bottom of an article page, which submits the article's ID as a foreign key (so the comment can be associated with the article), then everything is fine. If the ID is somehow used to set the primary key of the new comment, then this is not good. Hope it was a false alarm.
Alex Reisner
+1  A: 

If you are trying to create a new object, you can set the default values when you first instantiate a new object

def new
  @revision = Revision.new(
    :background_title => "Some Background Title",
    :title => "Some Title"
  )
end

then automatically the value of the fields will be set accordingly =) it's just that simple ;-)

Staelen