0

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)
0

3 Answers 3

2

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])
Sign up to request clarification or add additional context in comments.

Comments

0

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 %>)

Comments

0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.