将id从视图旁路到控制器以创建具有关系的模型

时间:2013-11-27 14:30:37

标签: ruby-on-rails view model controller mongoid

我正在尝试为餐馆创建菜单。菜单必须有一个餐厅,但我不知道如何绕过id或如何解决问题。

这是我的路线:

scope '(:locale)' do
resources :restaurants do
end
resources :menus
end
这是我的餐厅模特:

has_many :menus, dependent: :destroy
accepts_nested_attributes_for :address, :menus

我的菜单型号:

class Menu
include Mongoid::Document

belongs_to :restaurant
accepts_nested_attributes_for :restaurant

validates :name, presence: true
validates :description, presence: true
validates :restaurant, presence: true

field :name, type: String
field :description, type: String
end

来自餐馆show.erb我称之为:

<%= link_to 'new Menu', new_menu_path(@restaurant) %>
菜单控制器中的

我试图将它放入new或create方法中:

@resti = Restaurant.find(params[:restaurant_id])

但它不起作用..我真的不知道我应该如何解决这个问题..有谁能告诉我我该怎么办?

由于Restaurant.find

,这是错误
Problem: Calling Document.find with nil is invalid. Summary: Document.find 
expects the parameters to be 1 or more ids, and will return a single document 
if 1 id is provided, otherwise an array of documents if multiple ids are 
provided. Resolution: Most likely this is caused by passing parameters 
directly through to the find, and the parameter either is not present or 
the key from which it is accessed is incorrect.

先谢谢你

更新:当我这样做时,犹太人说嵌套路线

resources :restaurants do
  resources :menus
end

我在app / views / menus / new.html.erb

中收到此错误
undefined method `menus_path' for #<#<Class:0x007fb2937484c8>:0x007fb290d704e8>

<%= form_for(@menu) do |f| %>
<% if @menu.errors.any? %>
  <div id="error_explanation">
    <h2><%= pluralize(@menu.errors.count, "error") %> prohibited this menu from being saved:</h2>

1 个答案:

答案 0 :(得分:2)

一种方法是将restaurant_id参数显式传递给路径助手:

<%= link_to 'new Menu', new_menu_path(restaurant_id: @restaurant) %>

另一种方法是将menus资源嵌入到您的路径中的restaurants资源中:

resources :restaurants do
  resources :menus
end

然后在你看来:

<%= link_to 'new Menu', new_restaurant_menu_path(@restaurant) %>

修改

MenusController中,添加过滤器以自动分配@restaurant

before_filter :assign_restaurant

...
private
def assign_restaurant
    @restaurant = Restaurant.find(params[:restaurant_id])
end