damir
damir

Reputation: 2028

Bypassing id from view to controller to create a model with relation

i am trying to create a menu for a restaurant. A menu has to have a restaurant, but i dont know how to bypass the id or how to solve the problem.

here is my route:

scope '(:locale)' do
resources :restaurants do
end
resources :menus
end

this is my restaurant model:

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

my menu model:

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

from the restaurants show.erb im calling this:

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

in the menu controller i tried to put this into the new or create method:

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

but it is not working.. i really dont know how i should solve this.. can anybody tell me how i can do that?

this is the error because of the 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.

thank you in advanced

update: when i do as jef said nested route

resources :restaurants do
  resources :menus
end

i get this error in 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>

Upvotes: 0

Views: 102

Answers (1)

Jef
Jef

Reputation: 5474

One approach is to explicitly pass the restaurant_id parameter to the path helper :

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

Another is to nest the menus resource into the restaurants one into your routes :

resources :restaurants do
  resources :menus
end

Then in your view :

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

EDIT

In the MenusController, add a filter to automatically assign the @restaurant :

before_filter :assign_restaurant

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

Upvotes: 2

Related Questions