2016-10-11 103 views
0

我試圖創建一次具有多個不同模型實例的窗體。使用CRUD以軌道形式保存模型的多個實例

我有我的主要模型可視化。可視化(:title,:cover_image)has_many行。一行has_many窗格(:text_field,:圖像)

基本上,當用戶嘗試創建可視化時,他們可以輕鬆選擇封面圖像和標題。但是當我來到接下來的兩個級別時,我有點困惑。

提示用戶在窗體中創建一個新行,並且他們可以選擇每行1,2或3個窗格。每個窗格可以接受文本和圖像,但Row本身不一定具有任何屬性。

如何在此窗體中使用多個窗格生成多行?最終結果將需要擁有一堆由許多窗格組成的行。我甚至可以在鐵軌上做到這一點?

感謝您的幫助!

+0

是的,Rails在這方面很出色。 'accept_nested_attributes_for'是你需要閱讀的內容。 – Swards

+0

請參考導軌指南來構建複雜的表單[http://guides.rubyonrails.org/form_helpers.html#building-complex-forms] – johnnynemonic

回答

0

你可以在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的有點先進的,但生命的救星,當涉及到,你有許多不同類型的一個模型的形式和你不希望所有的雜亂的大型應用程式。

+0

哇謝謝,這太棒了! 因此,我需要製作一個SoMuch控制器,而不是將該代碼放在我的Visualizations控制器中嗎? – scotchpasta

+0

沒問題。不,你想保留你的控制器來處理你的視圖,你創建的SoMuch類只是一個無表模型,你將在你的代碼中執行驗證。使用正常的控制器和其中的動作,只需調用它所示的SoMuch類即可。 – bkunzi01

+0

我看到你的新堆棧,所以你可能已經知道另一個小技巧,所有的控制器都可以使用所有的模型類。 – bkunzi01

相關問題