How to setup a global variable in a controller

故事扮演 提交于 2020-01-03 21:48:55

问题


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


回答1:


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

and using $b instead of @b does the trick




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/7136652/how-to-setup-a-global-variable-in-a-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!