首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何将nested_form gem与新的与现有嵌套模型对象的不同部分一起使用?

关于如何将nested_form gem与新的与现有嵌套模型对象的不同部分一起使用,以下是一个完善且全面的答案:

首先,nested_form gem是一个Ruby on Rails插件,它允许您在一个表单中创建和编辑多个嵌套模型对象。要使用nested_form gem,您需要在Gemfile中添加以下代码:

代码语言:txt
复制
gem 'nested_form'

然后运行bundle install命令来安装nested_form gem。

接下来,您需要在主模型和嵌套模型之间建立关联。例如,如果您有一个名为Survey的主模型和一个名为Question的嵌套模型,您需要在Survey模型中添加以下代码:

代码语言:ruby
复制
class Survey< ApplicationRecord
  has_many :questions, dependent: :destroy
  accepts_nested_attributes_for :questions, allow_destroy: true
end

Question模型中,您需要添加以下代码:

代码语言:ruby
复制
class Question< ApplicationRecord
  belongs_to :survey
end

接下来,您需要在主模型的表单中添加嵌套模型的表单。例如,在Survey模型的表单中添加Question模型的表单,您可以使用以下代码:

代码语言:html
复制
<%= nested_form_for @survey do |f| %>
  <%= f.label :title %>
  <%= f.text_field :title %>

  <%= f.fields_for :questions do |question_form| %>
    <%= question_form.label :content, "Question" %>
    <%= question_form.text_field :content %>
    <%= question_form.link_to_remove "Remove Question" %>
  <% end %>

  <%= f.link_to_add "Add Question", :questions %>
  <%= f.submit %>
<% end %>

在这个例子中,nested_form_for方法用于创建一个表单,fields_for方法用于添加嵌套模型的表单。link_to_remove方法用于删除现有的嵌套模型对象,link_to_add方法用于添加新的嵌套模型对象。

最后,您需要在控制器中处理表单提交。例如,在SurveysController中,您可以使用以下代码:

代码语言:ruby
复制
class SurveysController< ApplicationController
  def new
    @survey = Survey.new
    @survey.questions.build
  end

  def create
    @survey = Survey.new(survey_params)
    if @survey.save
      redirect_to @survey
    else
      render :new
    end
  end

  private

  def survey_params
    params.require(:survey).permit(:title, questions_attributes: [:id, :content, :_destroy])
  end
end

在这个例子中,survey_params方法用于允许titlequestions_attributes参数的传递。questions_attributes参数包含了嵌套模型对象的属性,例如content_destroy

现在,您已经成功地将nested_form gem与新的与现有嵌套模型对象的不同部分一起使用了。您可以使用nested_form gem创建和编辑多个嵌套模型对象,并且可以轻松地添加和删除嵌套模型对象。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的结果

领券