本文介绍了Rails模型设计决策的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,为了简化我的应用程序,我的应用程序中有3个主要模型;城市,餐厅和食谱.一个城市有很多餐馆,而餐馆有很多食谱.每个城市都有一个页面,列出该城市的餐馆,同样,每个餐馆页面的页面中都列出了食谱.我的城市页面中还有一个添加新餐厅"按钮,当用户单击此按钮时,用户将被带到带有以下链接的新餐厅页面:

So to simplify what I have, there are 3 main models in my application; city, restaurant and recipe. A city has many restaurants and a restaurant has many recipes. Every city has a page that lists the restaurants in that city and similarly every restaurant page has recipes listed in their page. There is also a "Add new restaurant" button in my city page, when the user clicks on this the user is taken to the new restaurant page with the following link:

<%= link_to 'Add New Restaurant', new_restaurant_path %>

但是此页面是通用页面,用户可以将餐厅添加到任何城市,我如何修改我的设计,以便该新餐厅表单只能将新餐厅添加到该城市.

But this page is a generic page that the user can add a restaurant to any city, how do i modify my design so that, that new restaurant form would only add a new restaurant to that city.

感谢您的回答.所以这是我现在的餐厅创建方法..因为new_restaurant_path是一种表单,并且它具有除城市之外的其他参数.因此,我了解我可以通过执行@city = City.find(params [:city])来确定餐厅的城市,但是如何将其添加到此行的其余参数中@restaurant = Restaurant.new( params [:restaurant])

Thanks for the answers. So this is my restaurant create method right now.. Because new_restaurant_path is a form and it has other params than just a city. So i understand that I can figure out the city of my restaurant by doing @city = City.find(params[:city]) but how do I add this to the rest of the params in this line @restaurant = Restaurant.new(params[:restaurant])

def create
    @restaurant = Restaurant.new(params[:restaurant])

  end

推荐答案

有路线

您可以创建这样的路线:

With routes

You can create a route like this:

/cities/:city_id/restaurants/new

具有:

resources :city do
  resources :restaurants
end

和助手:

<%= link_to 'Add New Restaurant', new_city_restaurant_path(city) %>

在助手中带有参数

或者您可以在当前的路由帮助器中传递参数并在控制器中处理它:

With params in helper

Or you can pass a parameter in your current route helper and handle it in your controller:

<%= link_to 'Add New Restaurant', new_restaurant_path(city_id: city.id) %>

这将使用此URL:

/restaurants/new?city_id=123

对于两种方法,控制器

并在控制器中:

For both approaches, the controller

and in the controller:

def create
  city = City.find(params[:city_id])
  @restaurant = city.restaurants.build params[:restaurant]
  if @restaurant.save
    ...
end

这篇关于Rails模型设计决策的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 16:20