Search code examples
ruby-on-railsactiverecordassociationsmodelsone-to-many

Fetching data using one-many association


I am new to ror. I have 2 tables for group (called 'ab') and sub-group(called 'cd').Each group has several sub-groups.I have defined belongs_to and has_many relationship.

Model ab.rb

class Ab < ActiveRecord::Base
has_many:cds
end

Model cd.rb

class Cd < ActiveRecord::Base
belongs_to :ab
end

ab and cd have 2 columns each called title and Dscr.Do I have to create a join table (ab_cd_join_table)

I want to display a particular group and its sub-groups in a view.

The controller for the view

class DisplayController < ApplicationController

    def index
         @ab = Ab.find_by_title("XXXXXX")
             @cds = @ab.cds
                 for cd in @cds
                 logger.info cd.title
        end

I am using this in the view.

display view

<%= @ab.title %>

I don't know how to display the title and Dscr of different sub-groups belonging to the group = "XXXXXX"

Thanks in advance


Solution

  • What I think you're asking for is this in the view:

    <% @ab.cds.each do |cd| %>
    <h1><%= cd.title %></h1>
    <p><%= cd.description %></p>
    <% end %>
    

    and this in the controller:

    @ab = Ab.find_by_title("XXXXXX")
    

    That way you will display all cds for the ab-model matching "XXXXXX".

    Update: For belongs_to and has_many to work the model with belongs_to needs to have a column for the one that has has_many. In this case Cd needs to have a column named ab_id.

    rails g migration add_ab_id_to_cds ab_id:integer
    

    cd.ab_id needs to be the id of the corresponding Ab model.

    cds = Cd.where(<something>)
    cds.each do |cd|
      cd.ab_id = @ab.id
      cd.save
    end
    

    This maybe should be set upon creation of a Cd object, but just to test it out you can do like this.