On Nov 13, 12:40 am, jemminger <[EMAIL PROTECTED]> wrote:
> one suggestion:  don't put business logic in your views.  replace
> "FlightTime.new" with "@flight_time" and let your controller figure
> out if it should be a new or existing record.
>
> On Nov 12, 7:32 am, Alex Jonsson <[EMAIL PROTECTED]> wrote:
...
>
> > Now this works perfectly when _adding_ FlightTimes as I'm using a
> > FlightTime.new, but the issue I have is that I also want to be able to
> > edit the values. When I try to use this form for editing, all the
> > values in the boxes are emptied and anything I put in them are added
> > as new FlightTimes (obviously). There can only be one FlightTime per
> > FlightType per Flight, so to speak.
>

As per jemminger, if you want your action and template to both create
new objects and edit existing ones you need to put this logic into the
action in the controller.

So you might have:
  if params[:id]
    @foo=Foo.find(params[:id])
  else
    @foo=Foo.new
  end

In your view, you can then get rails to put whatever values are
currently in @foo into your fields:
  form_for :foo , :url ... do |f|
    f.text_field :field1
    ...
  end

or:
  fields_for :foo do |f|
    f.text_field :field1
    ...
  end

and rails will automagic in @foo.field1 as the value in that text
field because you specified ':foo'.
(Sorry, can't get my head around your models)

I was thinking that if you have an array of objects eg foo has_many
bars and you want to edit all those bars, then in the view you could
loop thru the array with an index eg:

  @foo.bars.each_with_index do |bar,idx|
    fields_for "bars[#{idx}]" , bar do |b|
      b.text_field :field1
      ...
    end
    ...
  end

Which, on submission, will generate
  params['bars']['0']['field1'] => <some-value>
  etc
Not sure if that's good but I think it works.
You could skip the whole 'with_index' thing if it's just has_one.

You'll also need to embed id value for each record into a hidden field
in your form if you're editing an existing item so that you can find
it and update it instead of creating a new object when the form is
submitted.
There are security implications here - people can post a random id
instead - so you need to think that through carefully.

--
Daniel Bush
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to