如何为两个不同的模型建立关联以属于一个类别模型

时间:2018-11-30 15:20:38

标签: ruby-on-rails ruby-on-rails-5 associations model-associations

因此,我有以下3种模型:优惠券,位置和类别。我想建立这样的关联:

  • 类别同时具有优惠券和与之相关的地点
  • 优惠券属于几个类别
  • 地点属于几个类别。

我将如何实现关联?

我目前拥有的东西:

模型

Coupon model
class Coupon < ApplicationRecord
  belongs_to :category
end

放置模型

class Place < ApplicationRecord
  belongs_to :category
end

类别模型

class Category < ApplicationRecord
  has_many :coupons
  has_many :places
end

控制器: 优惠券控制器:

class CouponsController < ApplicationController
  before_action :find_coupon, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except: [:index, :show]

  def index
    if params[:category].blank?
      @coupons = Coupon.all.order("created_at DESC")
    else
      @category_id = Category.find_by(name: params[:category]).id
      @coupons = Coupon.where(category_id: @category_id).order("created_at DESC")
    end
  end

  def show
  end

  def new
    @coupon = Coupon.new
    @categories = Category.all.each do |category|
      category
    end
  end

  def create
    @coupon = Coupon.new(coupon_params)
    if @coupon.save
      redirect_to @coupon
    else
      render 'new'
    end
    @categories = Category.all.each do |category|
      category
    end
  end

  def edit
    @categories = Category.all.each do |category|
      category
    end
  end

  def update
    @categories = Category.all.each do |category|
      category
    end
    if @coupon.update(coupon_params)
      redirect_to @coupon
    else
      render "edit"
    end
  end

  def destroy
    if @coupon.destroy
      redirect_to root_path
    end
  end




  private

  def coupon_params
    params.require(:coupon).permit(:title, :category_id, :description, :company)
  end

  def find_coupon
    @coupon = Coupon.find(params[:id])
  end

end

位置控制器:

class PlacesController < ApplicationController
  before_action :set_place, only: [:show, :edit, :update, :destroy]


  def index
    @places = Place.all
  end

  def show
  end

  def new
    @place = Place.new
    @categories = Category.all.each do |category|
      category
    end
  end

  def edit
  end

  def create
    @place = Place.new(place_params)
    respond_to do |format|
      if @place.save
        format.html { redirect_to @place, notice: 'Place was successfully created.' }
        format.json { render :show, status: :created, location: @place }
      else
        format.html { render :new }
        format.json { render json: @place.errors, status: :unprocessable_entity }
      end
    end
    @categories = Category.all.each do |category|
      category
    end
  end

  def update
    respond_to do |format|
      if @place.update(place_params)
        format.html { redirect_to @place, notice: 'Place was successfully updated.' }
        format.json { render :show, status: :ok, location: @place }
      else
        format.html { render :edit }
        format.json { render json: @place.errors, status: :unprocessable_entity }
      end
    end
    @categories = Category.all.each do |category|
      category
    end

  end

  def destroy
    @place.destroy
    respond_to do |format|
      format.html { redirect_to places_url, notice: 'Place was successfully destroyed.' }
      format.json { head :no_content }
    end
    @categories = Category.all.each do |category|
      category
    end

  end

  private

    def set_place
      @place = Place.find(params[:id])
    end

    def place_params
      params.require(:place).permit(:name, :category_id, :description, :address1, :address2, :city, :region, :phone, :email)
    end
end

观看次数: _sidebar部分:

#sidebar-wrapper
  %ul.sidebar-nav
    %li.sidebar-brand
      %a{:href => root_path}
        Shopperbait
    %li
    - @Category.all.each do |category|
      = link_to category.name, coupons_path(category: category.name)

application.html.haml:

!!!
%html
%head
  %title ""
  %meta{:charset => "utf-8"}/
  %meta{:content => "width=device-width, initial-scale=1, shrink-to-fit=no", :name => "viewport"}/
  %meta{:content => "ie=edge", "http-equiv" => "x-ua-compatible"}
  / Font Awesome
  %link{:crossorigin => "anonymous", :href => "https://use.fontawesome.com/releases/v5.4.2/css/all.css", :integrity => "sha384-/rXc/GQVaYpyDdyxK+ecHPVYJSN9bmVFBvjA/9eOB+pb3F2w2N6fc5qB9Ew5yIns", :rel => "stylesheet"}


  = stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload'
  = javascript_include_tag 'application', 'data-turbolinks-track': 'reload'
  = csrf_meta_tags
%body
  = render 'shared/navbar'
  = render 'shared/sidebar'

模式:

ActiveRecord::Schema.define(version: 20181129131201) do

  create_table "categories", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "coupons", force: :cascade do |t|
    t.string "title"
    t.text "description"
    t.string "company"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "category_id"
  end

  create_table "places", force: :cascade do |t|
    t.string "name"
    t.text "description"
    t.string "address1"
    t.string "address2"
    t.string "city"
    t.string "region"
    t.string "phone"
    t.string "email"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "category_id"
  end
end

此外,我希望能够在侧边栏中显示类别的链接。视图的代码将是什么?我的侧边栏不起作用

1 个答案:

答案 0 :(得分:0)

您将要开始使用Ruby on Rails Guides,因为它涵盖了很多基础知识,例如关联。您在上述示例中所指的可能是has_many :through关联的一个好用例。我之前链接的网站(Associations)上有更多详细信息。

关于第二个问题以及如何在侧栏中显示链接,您将要遍历所有类别,并为每个类别显示一个链接。遍历记录是非常的基本知识。您编写的代码在哪里?