2016-10-11 104 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

相关问题