以轨道方式编辑相关模型

时间:2015-07-13 17:25:08

标签: ruby-on-rails associations models

我有一个模特&#34;学生&#34;每个学生都有很多父母(父母餐桌上的母亲和父亲)。在我的UI中,我希望能够在同一页面上添加父母和学生。所以,当我点击&#34;添加学生&#34;观点&#39;学生/新&#39;被渲染。在这个视图中,我有一个常规的东西,即添加学生(<% form_for @student....)到目前为止一切都很好。但是现在我也希望在同一页面上提供为这名学生添加母亲和父亲的表格。我知道我可以链接到父母/新的&#39;在某个地方,但在我看来这并不是真正的用户友好。

我有什么选择,你会推荐什么?

3 个答案:

答案 0 :(得分:2)

您最好的选择是将public static void showNotExist(JPanel panel, String action) { JOptionPane.showMessageDialog(rootPane, new JLabel(action.concat(" doesn't exist."), 2)); } nested_forms一起使用,如下所示

accepts_nested_attributes_for

答案 1 :(得分:1)

form内,您可以添加fields_for帮助

<%= fields_for @student.father do |father| %>
  <% father.text_field :name %> # will be appropriate father name
  ....
<% end %>

同时检查rails fields_for

答案 2 :(得分:0)

我使用ObjectForm概念:

Here is one good article about this pattern.

以下是对实施的介绍:

Class Student < ActiveRecord::Base
  has_many :parents
end

class CompleteStudentForm
  include ActiveModel::Model

  attr_acessor :name, :age #student attributes
  attr_accessor :father_name, :mother_name #assuming that Parent model has only the :name attribute

  validates_presence_of :name, :age
  # simply add custom validation messages for fields
  validates_presence_of :father_name, message: 'Fill your father name'
  validates_presence_of :mother_name, message: 'Fill your mother name'

  def save
    persist! if valid?
  end

  private
  def persist!
    student = Student.new(name: @name, age: @age)
    student.parents << Parent.new(name: @father_name)
    student.parents << Parent.new(name: @mother_name)
    student.save!
  end
end


class StudentController 

  def create
    @student = CompleteStudentForm.new(params[:complete_student_form])

    if @student.save
      redirect_to :show, @student
    else
      render :new
    end
  end
end