开发者

how to pass instance variable to another view in rails

Hey. I think I am in a mind trap here. I am using Rails 2. In the index view of my controller I set up something like

def index
  @posts = Post.all
end

so that I can use @posts in my index, e.g. each-do. Id like to pass @posts to a custom made view, in where I can use the same variable aga开发者_运维技巧in. This I want to do over a link from the index view. Something like that:

link_to "newpage", {:controller => 'posts', :action => 'newmethod', :param => @posts}

What I have created so far is a new method in my Post controller. A new view. And and a new route to that site. Any suggestions? thx for your time


You're going to have to collapse those values into something that will fit in a URL, then decode them later. For instance:

# Put this in your helper method module PostsHelper
def post_ids
  @posts.collect(&:id).join(',')
end

Your adjusted link would be:

link_to "newpage", {:controller => 'posts', :action => 'newmethod', :param => post_ids }

When you fetch the next page you'll need to decode these by retrieving them again:

@posts = Posts.find(params[:param].split(/,/))

There's no way to pass an instance variable between requests because they are explicitly cleared out.

As a note, try and use the generated route methods instead of the hash-style declaration. You would probably have a route already listed in rake routes:

# Instead of { :controller => 'posts', :action => 'new', :param => post_ids }
new_post_path(:param => post_ids)

These generated methods are much more readable in practice and have the advantage of being configurable later if you want to re-interpret what they mean by adjusting your routing table.

Another note is that if the list of IDs gets very large, you may not be able to encode them into a URL as the limit is about 1500 bytes. You may instead have to serialize the conditions used to generate the list in the first place and then re-run those again later. So long as you're dealing with tens of items and not hundreds you should be okay, though.


In your controller

def newmethod
   @posts = Post.all
end

You can't pass all your models in a link ! The @posts var in the index action disappears after the request


I know that store arbitrary data in session is not a best practice, but in some cases this approach is simple and easy.

In your controller:

def balabala
  #...
  session[:your_var] = "this is the var used in another view&action!"
  # ...
end

In any other pages:

<%=  session[:your_var] %>

That's it. ugly, not MVC at all. :) Only recommended for very rare cases. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜