Clilking on a link should replace that link with a form


#1

Hi everyone!

I’m new to Ruby and JS, and there is a problem I’m trying to solve:
I need a link that, when clicked, transforms into a form for inputting
data. I have next code:

(show.html.erb)

<%= link_to_remote 'New Journal', :url => { :action => :expand_create_form, :controller => :journals, :user_id => @user.id } %>

(expand_create_form.js.rjs)
page[:new_journal].replace_html :partial => “create”,
:object => @user

The problem is I don’t want to use the controller, is there some
shortcut to call rjs code when user clicks on “New Journal” link?


#2

You could do something like this:

<%= link_to_function ‘New Journal’, “Element.replace(this, #{ render
(:partial => “create”,
:object => @user).inspect})”%>

check here for some gotchas with rendering partials this way:
http://tracesof.blogspot.com/2009/02/rails-partials-in-javascript-functions.html

Maybe a much nicer solution in this case would be to render the form
in a hidden div below the link and then just hide the link and un-hide
the form when the link is clicked. Like so:

<%= link_to_function 'New Journal', "this.hide(); $ ('new_journal_form').show()" %>
<div id="new_journal_form" style="display:none">
     <%= render :partial => "create", :object => @user %>
</div>

#3

Ha, just thought of a much better way:

(show.html.erb)

<%= link_to_function 'New Journal' do |page| page[:new_journal].replace_html :partial => "create", :object => @user end %>

#4

Why are you opposed to using the controller?

In any case, you can drop the RJS into app/views/journals/
expand_create_form.js.rjs
and it should work. That is the shortcut…

–Matt J.

On Feb 18, 5:38 pm, Andrew removed_email_address@domain.invalid wrote:

Hi everyone!

I’m new to Ruby and JS, and there is a problem I’m trying to solve:
I need a link that, when clicked, transforms into a form for inputting
data. I have next code: