你可以在rails中做任何事情!在我看来,最好的方法是创建所谓的表单模型,因为这个表单将会有很多事情发生,而且您不希望让一些模型出现验证错误,以及您的应用程序的一个视图。要做到这一点,你基本上要创建一个类,它将获取所有这些信息,运行你需要的任何验证,然后创建任何你需要的记录。要做到这一点,让我们创建名为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的有点先进的,但生命的救星,当涉及到,你有许多不同类型的一个模型的形式和你不希望所有的杂乱的大型应用程式。
是的,Rails在这方面很出色。 'accept_nested_attributes_for'是你需要阅读的内容。 – Swards
请参考导轨指南来构建复杂的表单[http://guides.rubyonrails.org/form_helpers.html#building-complex-forms] – johnnynemonic