开发者

How do I access an instance variable from another controller?

开发者 https://www.devze.com 2023-01-24 19:21 出处:网络
So I have two models & controllers. Projects and Designers. In my designers index view, I want it to show a list of all the projects that the designer has.

So I have two models & controllers. Projects and Designers.

In my designers index view, I want it to show a list of all the projects that the designer has.

However, when I do a simple query like this:

<% @projects.each do |project| %>
  <tr>
    <td><%= link_to 'Show', project %></td>
    <td><%= link_to 'E开发者_如何转开发dit', edit_project_path(project) %></td>
    <td><%= link_to 'Destroy', project, :confirm => 'Are you sure?', :method => :delete %></td>
  </tr>
<% end %>

From the index.html.erb in the Designers view, it gives me the following error:

NoMethodError in Designers#index
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each

However, when I run that EXACT code from the index.html.erb file in the projects view, it works perfectly.

So how am I able to access that controller or at least data from the view of another controller? Do I have to add a projects variable (where it queries the db) to my index object in my designers controller?

Thanks.


UPDATED TO USE A SINGLE DESIGNER RECORD

You should use associations. Add this to your models.

class Designer < ActiveRecord::Base
  has_many :projects
end

class Project < ActiveRecord::Base
  belongs_to :designer
end

Your view should look like this:

<% @designer.projects.each do |project| %>  

<% end %>

More info on associations here: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html


Figured out one way to do it. All I had to do was add an instance variable in my designers controller:

@projects = Project.all

But...that's not very DRY. Does anyone have a more elegant 'DRY' solution, so if I want to access other variables in other controllers I can do that easily without having to re-create them in the current controller?

Thanks.


In your designers controller, you need to set the @projects instance variable to only those projects belonging to the signed in designer, correct?

You'll need something like this:

def index

  @projects = Project.where(:user_id => where ever you've stored your userid) 

end

I hope this helps.

0

精彩评论

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

关注公众号