Search code examples
ruby-on-railsassociationshas-manyhas-one

List all models belonging to another model in rails


In the show view for the 'service' model I want to be able to show all of the 'reviews' that are associated with this service. Need to know what to put in the 'service' show view as well as the 'service'/'review' controller.

Service model:

class Service < ActiveRecord::Base
  has_many :reviews
end

Review model:

class Review < ActiveRecord::Base
  has_one :service
  belongs_to :service
end

Service show view:

<table>
<thead>
    <tr>
      <th>Name</th>
      <th>Date</th>
      <th>Review</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @reviews.each do |review| %>
      <tr>
        <td><%= review.name %></td>
        <td><%= review.date %></td>
        <td><%= review.review %></td>
        <td><%= link_to 'Show', review %></td>
        <td><%= link_to 'Edit', edit_review_path(review) %></td>
        <td><%= link_to 'Destroy', review, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

Review schema:

  create_table "reviews", force: true do |t|
    t.string   "name"
    t.string   "date"
    t.text     "review"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "service_id"
  end

Review controller:

def index
    @reviews = Review.all
    respond_with(@reviews)
  end

  def show
    respond_with(@review)
  end

  def new
    @review = Review.new
    respond_with(@review)
  end

  def edit
  end

  def create
    @review = Review.new(review_params)
    @review.save
    respond_with(@review)
  end

Service controller:

  def new
   @service = Service.new
  end

  # GET /services/1/edit
  def edit
  end

  # POST /services
  # POST /services.json
  def create
    @service = Service.new(service_params)

    respond_to do |format|
      if @service.save
        format.html { redirect_to @service, notice: 'Service was successfully created.' }
        format.json { render :show, status: :created, location: @service }
      else
        format.html { render :new }
        format.json { render json: @service.errors, status: :unprocessable_entity }
      end
    end
  end

Solution

  • If you want to show all of the reviews that are associated with the service in the service show page then, you need to tweak your service_controller show action like this

    def show
      @service = Service.find(params[:id])
      @reviews = @service.reviews
    end