Timmy Von Heiss
Timmy Von Heiss

Reputation: 2218

What is the difference between using params[:foo] and @foo?

ApplicationController
before_action :example_filter 

def example_filter 
  params[:foo] = '1' if #somethinghere
  @foo         = '1' if #somethinghere
end

NewsController

if @foo         == '1' #somethinghere
if params[:foo] == '1' #somethinghere

What are the differences or benefits between using @foo or params[:foo] in this situation?

One difference is that the user could pass params[:foo] themselves in the query string:

example.com/news?foo=1

Upvotes: 1

Views: 122

Answers (1)

oklas
oklas

Reputation: 8240

The @foo is object member. The params[:foo] is request param. The params[:foo] - may not have objects it may be only string or array of string (because it brought from request).

The code params[:foo] = 1 which you write is overwriting request params.

Better to use code like this:

ApplicationController
before_action :example_filter 

def example_filter 
  @foo = params[:foo] 
  @foo = 'something' if #somethinghere
end

# somewhere    
if @foo == '1' #somethinghere

Upvotes: 2

Related Questions