开发者

How to setup a global variable in a controller

I take inputs from users

In my index action开发者_运维问答 i have:

    @b = Ece.find_by_code("#{params[:course]}")

I want to use the value stored in @b in my show action as well as in index action.

In my show action i want to do something like this:

<p><%= link_to "Forum", href="/courses/#{Course.find_by_courseCode(<%= @b %>).id}", :class=>"question_button round" %>

How can i setup @b to be global so that both these actions can use it

Note: Ece and Course are two different models


I just wanted to use a way to declare @b to be global.

and using $b instead of @b does the trick


You could include it in a before filter like this:

before_filter :find_b, :only => [:index, :show]

# Standard controller actions here.

private
def find_b
  @b = Ece.find_by_code("#{params[:course]}")
end

Controller filters are a part of ActionController and you can find documentation on them here. In addition to before filters that run before an action there are also after filters and around filters which run around and after an action respectively.


In Rails it is not good practice to define @b somewhere you cannot see it being defined, as you may find it hard to figure our what's going on in the controller when you look back at it later on.

I suggest you set @b explicitly at the start of both the show and the index action: in other words, do repeat your

@b = Ece.find...

in each of the show and index actions - which is what you are already doing, I believe.

If you do want to clean up the controller code a bit, then do define a private function

private
def find_b(my_params)
    @b = Ece.find_by_code(my_params)
end

so that now your controller show and index actions set @b this way

@b = find_b("#{params[:course]}")

Now you have cleaner code, but at the same time you immediately know by looking at the controller that you are setting @b and that you are using params to do so.

As for the link you want to add in your show action, don't find the course Course.find_by_courseCode in the view - keep the view cleaner - and move that to the bit controller. So now your show action in the controller will have a line like this

@course = Course.find_by_id( @b.id )

and you can write your view link more cleanly as

<%= link_to 'Forum', @course, :class=>"question_button round" %>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜