jeudi 5 avril 2018

ROR Many to many association ,index page

I'm new to rails and i'm building this application which have 3 models Customer, Ad, CustomerAd where seen is params customer_ad I want CustomerAd to display all Ad and Customer watch them So when Customer click on one of Ads list (show ad) CustomerAd will update seen to true
I'm using:

Customer
  has_many :customer_ads
  has_many :ads through: :customer_ads

Ad
  has_many :customer_ads
  has_many :customers through: :customer_ads

CustomerAd
  belongs_to :customer
  belongs_to :ad

At Ads controller

def show
  ad = Ad.find params[:id]
  Ad.cusomer_ads.update(seen: true)
end

View customer_ad index and controller

              %tbody                  
                - @ads.each do |ad| 
                  - if @customer_ad.seen == true
                    %tr#btn.seen{"data-link" => "#{ad_path(ad)}"}
                      %td
                        = ad.short_description
                        = ad.long_description

                  - else
                    %tr#btn.unseen{"data-link" => "#{ad_path(ad)}"}
                      %td
                        = ad.short_description
                        = ad.long_description

class CustomerAdsController < ApplicationController
  before_action :set_customer_ad, only: [:show, :edit, :update, :destroy]    
  def index        
    @ads = Ad.all
  end

  private
    def set_customer_ad
      @customer_ad = CustomerAd.find(params[:id])
    end


    def customer_ad_params
      params.require(:customer_ad).permit(:customer_id, :ad_id, :bought, :seen)
    end
end

Aucun commentaire:

Enregistrer un commentaire