我想使用“reform”gem 来创建具有嵌套属性的对象。我有模型:
class Dish < ActiveRecord::Base
belongs_to :lunch_set
end
class Side < ActiveRecord::Base
belongs_to :lunch_set
end
class LunchSet < ActiveRecord::Base
belongs_to :restaurant
belongs_to :day
has_one :dish
has_many :sides
end
午餐 Controller "new"方法:
def new
@lunch_set = @restaurant.lunch_sets.build
@form = LunchSetForm.new(dish: Dish.new, side: Side.new)
respond_to do |format|
format.html # new.html.erb
format.json { render json: @lunch_set }
end
end
路线文件:
namespace :admin do
resources :restaurants do
resources :lunch_sets
resources :days do
resources :lunch_sets
end
end
end
和午餐套餐
class LunchSetForm < Reform:Form
include DSL
include Reform::Form::ActiveRecord
property :name, on: :dish
property :name, on: :side
end
我的问题是如何构建views/admin/lunch_sets/_form.html,特别是考虑到这些路线?当我尝试时
= simple_form_for @form do |f|
= f.input :name
= f.input :name
.actions
= f.submit "Save"
但它给了我错误
undefined method `first' for nil:NilClass
并点入线
= simple_form_for @form do |f|
最佳答案
form_for(以及 simple_form_for)期望表单对象具有 ActiveModel 方法(例如 model_name)来确定如何命名表单及其输入并解析表单的操作 URL。通过包含 Reform::Form::ActiveRecord,您已经接近完成任务了,但是您还需要做一些事情:
require 'reform/rails'
class LunchSetForm < Reform:Form
include DSL
include Reform::Form::ActiveRecord
property :name, on: :dish
property :name, on: :side
model :dish
end
model :dish
行告诉 Reform 您希望表单的“主模型”成为 Dish 实例。这意味着它将使您的表单响应 ActiveModel 通常为普通 Rails 模型提供的方法,使用“主模型”为这些方法提供值。您的表单输入名称将类似于 dish[name]
等,它将发布到您的菜肴_url。您可以将您的模型
设置为您喜欢的任何内容,但是您选择的任何实例都需要传递到表单构造函数中。
关于ruby-on-rails - 使用 'reform' gem 和嵌套路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17507200/