T
T
The Whiz2013-07-15 20:30:13
Ruby on Rails
The Whiz, 2013-07-15 20:30:13

Using @var in link_to

Gentlemen ruby, help

me I'm trying to revive the link in the _header format

<%= link_to @company.name, current_company %>

First Doper got

NoMethodError in StaticPages#about - undefined method `name' for nil:NilClass

that the Static_pages controller does not know about any Companies, and therefore it was decided to change the static pages controller to:

def home @company = Company.new end def about @company = Company.new end
And so on. This, however, did not help much - the links instead of the name look like

/companies/2

How to solve the problem? Is it possible to do this without repeating in every controller method? Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Loremaster, 2013-07-16
@modernstyle

If you need the variable to be available in all (well, or a large number) methods, then you can do this:

before_filter :init_company
...
private

def init_company
  @company = Company.find(params[:id])
end

After that, your variable becomes available in all controller methods. In the case of rails 4, you can also replace before_filter with before_action , which will make the code more clear.
Apparently, you have quite a lot of errors: for some reason you are trying to create an object, instead of finding it. Also in the view: the second parameter in link_to must be of the form zzz_path .

J
jj_killer, 2013-07-15
@jj_killer

@company = Company.find(params[:id])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question