我正在尝试创建一个同时具有多个不同模型实例的表单。
我有我的主要模型可视化。可视化(:title,:cover_image) has_many行。行has_many窗格(:text_field,:image)
基本上,当用户试图创建可视化时,他们可以很容易地选择封面图像和标题。但当我进入下两个层次时,我有点困惑。
提示用户在表单中创建一个新行,他们可以选择每行1、2或3个窗格。每个窗格都可以接收文本和图像,但是Row本身并不一定有任何属性。
如何在此窗体中生成具有多个窗格的多行?最终结果将需要拥有一组由许多窗格组成的行。我甚至可以在rails上这样做吗?
谢谢你的帮助!
发布于 2016-10-11 20:51:32
你可以在铁轨上做任何事!在我看来,最好的方法是创建一个所谓的表单模型,因为这个表单将会有很多事情发生,而且您不想为您的应用程序的一个视图而陷入多个模型的验证中。要做到这一点,您基本上要创建一个类,它将接收所有这些信息,运行所需的验证,然后在任何模型中创建所需的任何记录。为此,让我们在您的模型文件夹中创建一个名为so_much.rb的新文件(您可以使用任何您想要的文件名,只需确保类的名称与文件相同,这样Rails就可以自动找到它了!)
然后在您的so_much.rb文件中做:
class SoMuch
include ActiveModel::Model #This gives us rails validations & model helpers
attr_accessor :visual_title
attr_accessor :visual_cover #These are virtual attributes so you can make as many as needed to handle all of your form fields. Obviously these aren't tied to a database table so we'll run our validations and then save them to their proper models as needed below!
#Add whatever other form fields youll have
validate :some_validator_i_made
def initialize(params={})
self.visual_title = params[:visual_title]
self.visual_cover = params[:visual_cover]
#Assign whatever fields you added here
end
def some_validator_i_made
if self.visual_title.blank?
errors.add(:visual_title, "This can't be blank!")
end
end
end现在,您可以进入正在处理此表单的控制器,并执行如下操作:
def new
@so_much = SoMuch.new
end
def create
user_input = SoMuch.new(form_params)
if user_input.valid? #This runs our validations before we try to save
#Save the params to their appropriate models
else
@errors = user_input.errors
end
end
private
def form_params
params.require(@so_much).permit(all your virtual attributes we just made here)
end然后,在您的视图中,您可以使用form_for设置@so_much,例如:
<%= form_for @so_much do %>
whatever virtual attributes etc
<% end %>表单模型在Rails中有点先进,但对于大型应用程序来说,它是一个生命保护程序,在这些应用程序中,一个模型有许多不同类型的表单,而且您不想要所有的杂乱。
https://stackoverflow.com/questions/39986172
复制相似问题