Reputation: 8587
I have a relational database, where something belongs to this, and where this has many of that... I have working example for a given URL parameters, but would like to know how to apply the same concept to a page where it iterates through ALL the database.
Controller
def index
@lists = List.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @lists }
end
end
@lists = List.all
is to get all the values in my database so I can use it in my view page and iterate that to display values.
However, I'd like to iterate it and then also get the id, and iterate through another table in my database based on the id. I have another method within the same controller that works (somehow, I don't know)
def show
@list = List.find(params[:id])
@idea = @list.ideas.build
respond_to do |format|
format.html # show.html.erb
format.json { render json: @list }
end
end
Where @list = List.find(params[:id])
gets the parameter in the url and then @idea = @list.ideas.build
somehow makes it relate to @list
where I can use this loop
<% @list.ideas.each do |idea| %>
<div>
<div class="list_idea_desc"><%= idea.description %></div>
</div>
<% end %>
to get the values from ideas
table and output inside a page within list
. But I can't output all lists
and all ideas
in the index page (without url parameter) if I'm iterating through this way:
<% @lists.each do |list| %>
<% @list.ideas.each do |idea| %>
<div>
<div class="list_idea_desc"><%= idea.description %></div>
</div>
<% end %>
<% end %>
Does this make sense? I guess I'm just trying to figure out how to get the id from the iteration of @lists
and then somehow connect the id with another table in my database?
Thanks!
Upvotes: 2
Views: 3775
Reputation: 9700
Actually, you can do exactly that. I believe if you change <% @list.ideas.each do |idea| %>
to <% list.ideas.each do |idea| %>
, it will work.
The problem is that @list
is an instance variable (probably one which is not set - I don't see it set anywhere), whereas list
is a local variable set by your iterator (.each
).
Note, incidentally, that this will likely start running quite slowly as the number of Lists in your database grows, because the server will make one call to fetch the Ideas associated with each one. You can solve this using eager loading.
Upvotes: 4