从另一个控制器的视图调用控制器

时间:2017-02-01 21:30:02

标签: ruby-on-rails ruby activerecord

我有一个餐厅控制器,并且在show方法中我呈现另一个控制器(菜肴)的形式

   #new.html.erb (from dishes controller)
   <%= render 'dishes/dish_form' %>

   #show.html.erb (from restaurant controller)
   <%= render template: 'dishes/new' %>

这是表格:

<%= form_for @dish, :url => { :controller => "dishes", action_name => "create" } do |f| %>
  <div class="field">
    <%= f.label :dish_name %>
    <%= f.text_field :name %>
  </div>
   <div class="field">
    <%= f.label :description %>
    <%= f.text_field :description %>
  </div>
  <div class="field">
    <%= f.label :image %>
    <%= f.file_field :avatar %>
  </div>
  <div class="actions">
    <%= f.submit 'Add new dish' %>
  </div>
<% end %>

但是当我尝试这样添加一道菜时,我有这个错误 enter image description here enter image description here

这是我的餐具控制器:

  def new
    @dish = Dish.new
  end

  def create
    @dish = Dish.new(dish_params)

    respond_to do |format|
      if @dish.save
        format.html { redirect_to @restaurant, notice: 'dish was successfully created.' }
        format.json { render action: 'show', status: :created, location: :restaurant }
      else
        format.html { render action: 'show', location: :restaurant }
        format.json { render json: @restaurant.errors, status: :unprocessable_entity }
      end
    end
  end 

  private
    def dish_params
      params.require(:dish).permit(:avatar, :name, :description)
    end

这是我的模特:

class Restaurant < ApplicationRecord
  has_many :dish, inverse_of: :restaurant
  accepts_nested_attributes_for :dish
end

class Dish < ApplicationRecord
  belongs_to :restaurant
end

我正在学习rails所以也许是一个愚蠢的错误,但我卡住了

2 个答案:

答案 0 :(得分:0)

你应该尝试将这个呈现给表单的控制器动作

@dish = Dish.new

直接拨打&#39;创建&#39; action rails缺少实例变量Dish.new。因此错误消息。通常rails的工作原理如下:

def new
@dish = Dish.new
end

而不是在&#39;提交&#39;上调用创建操作。 但是,因为看起来你从#show动作调用表单只是在那里添加这个代码,你会没事的。可能不是最好的解决方案,但它会像那样工作。添加到#show

@dish = Dish.new

对不起伙伴。是的@dish是正确的而不是:菜肴。

答案 1 :(得分:0)

行。 我最近的猜测是,你希望餐厅能够创造很多菜肴。 因此,您应该相应地设置模型:

#restaurants_model
 has_many :dishes
#dishes_model
belongs_to :restaurant

接下来是你在餐桌上添加一个名为restaurant_id的列 t.string :restaurant_id

比餐馆控制员#show

def show
end

如果您正常使用这些路线,例如

resources :restaurants
resources :dishes

餐厅控制器的show动作应该给你一个如下所示的网址:localhost:3000 / restaurants / 1 其中1是餐厅的id。

您希望通过添加隐藏字段来保存此菜单

=f.hidden_field :restaurant_id, value: @restaurant.id

你需要在餐馆控制器参数中允许restaurant_id,例如dish_params。只需添加

:restaurant_id

它应该没问题。这样,id将被保存到餐桌上,您可以稍后从那里调用它。 这让您有机会致电@ restaurant.dishes,这将展示该餐厅的所有菜肴。

如果您只想重定向,可以使用redirect :back 否则,您可以尝试使用隐藏的restaurant_id字段集成帮助程序以获取正确的餐厅

相关问题