I have this to calling the choose_category:
{ :action => :choose_category, :id => category } do %>And I have this method to calling the choose_category.js.rjs:
def choose_category
begin
category = Category.find(params[:id])
rescue
ActiveRecord::RecordNotFound
logger.error("Attempt to access invalid product #{params[:id]}")
# flash[:notice] 开发者_运维问答 = "Invalid product"
redirect_to :action => :index
else
respond_to { |format| format.js }
# redirect_to_index
end
end
I want to call back the category name, how can I do that? I try this, but it return nothing for me.
page.alert(@category.name)
Your problem is that @category isn't defined in your RJS template.
RJS files are essentially views that generate Javascript. Like views, they have access to instance variables set in the controller, but not local variables.
Putting this in the begin section of your action should solve your problem.
@category = Category.find(params[:id])
I'm not sure of this since I'm not very familiar with js and rjs, but I would add to your rjs something like this:
category_name = <%= @category.name %>;
and then
page.alert(category_name)
or just:
page.alert(<%= @category.name %>)
If you can write your own JavaScript why not use the Ruby's to_json() method to output your object in JSON to an embedded constant on your page and then write some JavaScript to access this variable and manipulate as needed?
精彩评论