开发者

Nested output with related models

I have a model Category and a model Weblink. Category has_many Weblink and Weblink belongs_to Category. Now I want to show all categories in a view and within a category all weblinks belonging to that category, something link this:

 <ul> 

<% @categories.each do |category| %>

  • <%= category.category_name %>
  • <% @weblinks.each do |weblink| %>
  • <%= weblink.category_name link_to weblink.link_name,开发者_运维百科 weblink.link_url %>
  • <% end %> <% end %>

    In the controller I have:

       @categories = Category.all
    

    @weblinks = Weblink.all This shows every category and within every category all weblinks, instead of just the ones which belong to the specific category. How can I fix this?


    Your view code should look like this

    <% @categories.each do |category| %>
       <%= category.name >
       <% category.weblinks.each do |weblink| %>
          <%= link_to weblink.name, weblink.link_url %>
       <% end -%>
    <% end -%>
    

    It your controller, when querying for all the categories you should also include the weblinks model, something like this:

    @categories = Category.all(:include => :weblinks)
    


    Scope the inner loop to the outer category using the macro you get with has_many:

    <% @categories.each do |category| %>
      <%= category.category_name %>
      <% category.weblinks.each do |weblink| %>
        <%= link_to weblink.link_name, weblink.link_url %>
      <% end %>
    <% end %>
    
    0

    上一篇:

    下一篇:

    精彩评论

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

    最新问答

    问答排行榜