I have a model called Company, and in the Show view have the following:
<div id = 'tags'>
<strong>Tags:</strong>
<% unless @company.tag_list.empty? %>
<%= @company.tag_list %>
<% end %>
<% for开发者_运维百科m_remote_tag(:url => {:action => 'update'},
:update => 'tags') do %>
<%= text_field :company, :tag_list %>
<%= submit_tag 'Save' %>
<% end %>
</div>
I am using acts_as_taggable_on gem.
This is the update method in the Company controller:
def update
@company = Company.find(params[:id])
if @company.update_attributes(params[:company])
flash[:notice] = "Successfully updated company."
redirect_to @company
else
render :action => 'edit'
end
end
I guess my desired result would be I could add tags, see them added via ajax, all without needing to Edit the model but from the show View, kind of like the way you can add tags in Wordpress.
UPDATE: This is the error I get (it looks like it isn't using the update action:
POST http://localhost:3000/companies/10
No action responded to 10. Actions: create, destroy, edit, email_this_week, index, new, show, and update
Hmmm, not sure why it is doing that....it should do update action, right? Do I need to do something in my routes (even though I specified the action?)
You are almost there.
First you create a partial tags
that renders your tags and your ajax-form (that you showed in your question).
Then inside your controller-method you write:
def update
@company = Company.find(params[:id])
if request.xhr?
# add the given tag to the company
@company.tags << params[:company][:taglist]
@company.save
render :partial => 'tags'
else
if @company.update_attributes(params[:company])
flash[:notice] = "Successfully updated company."
redirect_to @company
else
render :action => 'edit'
end
end
end
What i do: i test if the request is an ajax request (xhr?
) and then try to update the tags from the field that was given: you will have to correct that code i guess. I am assuming just doing update_attributes
does not work, as you will want to add a tag to a list of existing tags. If that succeeds, you render the partial which will replace the previous, because of the update
-option you specified in the form.
This should get you started.
To improve it further, you should add to each of your tags an image (a red cross) with a link to remove the given tag.
There are some jquery plugins which were called edit-in-place... Maybe this helps you:
https://stackoverflow.com/questions/708801/whats-the-best-edit-in-place-plugin-for-jquery
精彩评论