:onclick function executing on page load

The following code in my rhtml file creates an ‘event’ object when the
‘accept agreement’ link is clicked, but also creates an ‘event’ object
when the page loads.

<%= submit_tag ‘Accept Agreement’, :onclick => Event.create(:object_id
=> 1, :name => ‘agreement’, :date => Time.now).save! %>

How might I change my code so that an ‘event’ is created only upon
clicking?

Thanks,

Peter

On 9/17/07, Peter M. [email protected] wrote:

The following code in my rhtml file creates an ‘event’ object when the
‘accept agreement’ link is clicked, but also creates an ‘event’ object
when the page loads.

<%= submit_tag ‘Accept Agreement’, :onclick => Event.create(:object_id
=> 1, :name => ‘agreement’, :date => Time.now).save! %>

Erm, yeah, that’s messed up.

Event.create is Ruby code (I’m assuming Event is a model in your
application), and it’s being executed as the template is being
rendered. The return from save! (which is redundant, because create
saves the row) is passed as the content for the onclick attribute of
the generated submit button.

Rather than trying to “fix” this, I think you need to back up and walk
through a Rails tutorial so you can get the basic pattern down. For
instance, you will rarely (if ever) use an onclick event on a submit
button.

Bob S. wrote:

Erm, yeah, that’s messed up.

Event.create is Ruby code (I’m assuming Event is a model in your
application), and it’s being executed as the template is being
rendered. The return from save! (which is redundant, because create
saves the row) is passed as the content for the onclick attribute of
the generated submit button.

Rather than trying to “fix” this, I think you need to back up and walk
through a Rails tutorial so you can get the basic pattern down. For
instance, you will rarely (if ever) use an onclick event on a submit
button.

Yeah, I somehow thought I could get away with putting that in the view
code. I’ll just create the ‘event’ in the controller though
form_remote_tag. Thanks for your feedback!

Peter