我想使用'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
Lunchset 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
和LunchSetForm
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|
答案 0 :(得分:2)
form_for(反过来,simple_form_for)期望表单对象具有类似于model_name的ActiveModel方法,以弄清楚如何命名表单及其输入并解析表单的操作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]
等,它将发布到您的dishes_url。您可以将model
设置为您喜欢的任何内容,但是您选择的实例都需要传递给表单构造函数。