【问题标题】:Need help rails routing using model attribute需要帮助使用模型属性进行轨道路由
【发布时间】:2019-11-16 23:24:15
【问题描述】:

我目前正在学习 Rails,并且正在构建我的第一个 Rails 项目。我创建了一个 :restaurant 模型(以及其他模型 - 预订和用户),其中包含多个属性,其中包括 :city。这是我的架构:

create_table "restaurants", force: :cascade do |t|
    t.string "name"
    t.string "city"
    t.string "website"
    t.string "phone_number"
    t.integer "ratings"
    t.integer "capacity"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

在我的根“/”页面中,我将唯一的城市值显示为带有链接的列表。我希望用户可以通过点击他们所在或计划访问的城市来浏览餐馆(最好使用链接'/restaurants/#{city}'并通过该链接最终进入一个包含餐馆列表的页面那个城市。

我一直在试图弄清楚如何做到这一点,目前我的相关路线如下所示:

resources :restaurants do 
    resources :bookings
  end

我尝试将 :city 创建为嵌套资源,但这最终以 url '/restaurants/:restaurant_id/:city' 结尾,这不是我想要实现的。

但最重要的是,我无法弄清楚用户在根页面中单击的“城市”如何导致该城市中所有餐馆的页面。

任何建议都会很有帮助。

谢谢。

【问题讨论】:

    标签: ruby-on-rails activerecord routing


    【解决方案1】:

    路线非常灵活,给你很大的力量。

    第一种选择:我建议采用更传统的 Rails 方式:将您的城市划分为自己的模型,并将它们与餐厅联系起来。

    类似这样的:

    class City < ApplicationRecord
      has_many :restaurants, inverse_of: :city
      ...
    end
    
    class Restaurant < ApplicationRecord
      belongs_to: city, inverse_of: :restaurants
      ...
    end
    

    然后,我会稍微移动一下您的数据库:

    create_table :cities do |t|
      t.string :name, null: false
      t.timestamps
    end
    
    create_table :restaurants do |t|
      t.string :name
      t.references :city
      t.string :website
      t.string :phone_number
      t.integer :rating
      t.integer :capacity
    end
    

    这将使您走上嵌套路由的正确轨道,例如:

    /cities/:city_id/restaurants
    

    第二个选项是离开 RESTful 路径,玩转路由的灵活性:

    (我建议不要使用/restaurants/:city,直接使用/:city,但想法是一样的)

    # routes.rb
    # warning! Put this towards the very end of your file. Even then, any URL you try to hit that fits
    # this pattern will get sent to this controller action. e.g. "yoursite.com/badgers"
    # you'll need to explore handling RecordNotFound and redirecting someplace else 
    get '/:city', to: 'restaraunts#by_city', as: 'restaurants_by_city'
    

    现在在您的餐厅控制器中:

    class RestaurantsController < ApplicationController
      ...
      def by_city
        city = params[:city] # this will be whatever is in the url
    
        @restaurants = Restaurant.where(city: city)
    
        # you'll need some error handling:
        redirect to root_path if @restaurants.empty?
        ...
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 1970-01-01
      • 2020-02-21
      • 2023-04-01
      • 2010-09-13
      • 1970-01-01
      相关资源
      最近更新 更多