你可以在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