Ruby on rails 需要使用模型属性的rails路由帮助吗

Ruby on rails 需要使用模型属性的rails路由帮助吗,ruby-on-rails,activerecord,routing,Ruby On Rails,Activerecord,Routing,我目前正在学习rails,并正在构建我的第一个rails项目。我创建了一个:restaurant模型(以及其他模型-bookings和user),其中包含几个属性,包括:city。以下是我的模式: create_table "restaurants", force: :cascade do |t| t.string "name" t.string "city" t.string "website" t.string "phone_number" t.int

我目前正在学习rails,并正在构建我的第一个rails项目。我创建了一个:restaurant模型(以及其他模型-bookings和user),其中包含几个属性,包括: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\u id/:city”并不是我想要实现的

但最重要的是,我无法计算出用户在根页面中单击的“城市”如何指向该城市所有餐厅的页面

任何建议都会很有帮助


谢谢。

路线非常灵活,给您很大的动力

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

大概是这样的:

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

class Restaurant < ApplicationRecord
  belongs_to: city, inverse_of: :restaurants
  ...
end
这将使您走上嵌套布线的正确轨道,如:

/cities/:city_id/restaurants
第二种选择是走出宁静之路,发挥路线的灵活性:

(我建议远离
/餐馆/:city
,只使用
/: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
class RestaurantController
# 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