【问题标题】:How do I set up associations for two different models to belong to one categories model如何为两个不同的模型设置关联以属于一个类别模型
【发布时间】:2018-11-30 15:20:37
【问题描述】:

所以我有这 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

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

【问题讨论】:

  • 欢迎来到 Stack Overflow!这不是真正的代码编写服务。如果您展示您已经尝试过的内容并告诉我们哪些有效,哪些无效,这通常会很有帮助。或者,至少,告诉我们您研究了什么,什么是有意义的,什么是令人困惑的。
  • 我进行了编辑以包含我当前的代码

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-23
    相关资源
    最近更新 更多