我试图一次创建一个包含多个不同模型实例的表单。
我有我的主要模型可视化。可视化(:title,:cover_image)has_many Rows。一行has_many窗格(:text_field,:image)
基本上,当用户尝试创建可视化时,他们可以轻松地选择封面图像和标题。但是当我来到接下来的两个级别时,我有点困惑。
提示用户在表单中创建一个新行,他们可以选择每行1,2或3个窗格。每个窗格都可以包含文本和图像,但Row本身不一定具有任何属性。
如何在此表单中生成具有多个窗格的多个行?最终结果需要拥有一堆由许多窗格组成的行。我甚至可以在铁轨上这样做吗?
感谢您的帮助!
答案 0 :(得分:0)
你可以在铁轨上做任何事情!在我看来,最好的方法是创建一个所谓的表单模型,因为这个表单会有很多事情发生,你不想让几个带有验证的模型陷入困境,例如你的应用程序的一个视图。要做到这一点,你基本上要创建一个类,它将获取所有这些信息,运行你需要的任何验证,然后在你拥有的任何模型中创建你需要的任何记录。为此,我们可以在名为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
然后在您的视图中,您可以使用@so_much
设置form_for,如:
<%= form_for @so_much do %>
whatever virtual attributes etc
<% end %>
表单模型在Rails中有点先进,但对于较大的应用程序而言,它们可以节省生命,在这些应用程序中,您可以为一个模型提供多种不同类型的表单,而且您不需要所有的混乱。