I’m working on adding tagging to my application, to add tags to a
mailing list of fans.
I’ve got checkboxes to select each fan, and a dropdown select list
with the current tags and a “New tag” option. If you choose “New
tag”, a Javascript prompt asks you to name the new tag, and then it
calls the method which adds the tags to the list of fans.
So far so good, but the last thing I want it to do is refresh the list
of fans with the new tags applied. Right now it’s refreshing the list
of fans, except it’s the previous list of fans without the new tags.
If I manually reload the page, the tags are clearly there, but my
guess is the inline RJS is happening too fast, so that it’s refreshing
the fans_list DIV before the new tags have been applied? I’m not
sure.
Here’s the function called from my form_observer:
FansController#new_tag
def new_tag
if params[:tag] == “New tag”
render :update do |page|
session[:fans] = params[:fans]
unless params[:fans].empty?
page.call(“x_add_tag”) @fans = Fan.paginate :all, :per_page => 25, :page =>
params[:p], :order => “created_at DESC”
page.replace_html ‘fans_list’, :partial =>
‘fans_list’, :locals => {:fans => @fans, :what => “FUNK YEAH”}
end
end
else
render nil, :layout => false
end
end
Are you creating the new fan here? If so, isn’t this going to get
executed in the browser? So you are sending back javascript to:
add the tag
update the select list
Doesn’t this mean the new tag is only added after another trip to the
browser but the new fan list is evaluated in the method? Or have I
interpreted this all wrong?
<%= javascript_tag %Q{
function x_add_tag()
{
var tag = prompt(‘Name for new tag’, ‘’);
if (tag == null) return;
#{remote_function :url => tag_fans_path(:fans => @fans_to_tag), :with => “‘tag=’ + tag” }
}
} %>
And here’s the “tag” action in fans_controller.rb:
def tag
fans = params[:fans]
fans ||= session[:fans]
for f in fans
fan = Fan.find(f[1])
tag ||= params[:tag]
tag = params[:fan][:tag] if params[:fan]
fan.tag_list.add(tag)
fan.save
end
redirect_to fans_path
end
#new_tag renders some javascript which includes:
a. something to popup asking for the new tag, then remote calling #tag
b. something to replace the fans list (after getting the current
list)
the javascript is evaluated in the browser:
a. displaying the popup and calling the remote function
b. setting the selection list from @fans as it was when #new_tag ran
#tag adds the new tag
I think you need to have your replace of the selection list in the
render of #tag so that @fans is evaluated after the new tag is created.