使用嵌套属性创建相关数据

时间:2015-04-22 06:11:31

标签: ruby ruby-on-rails-4 strong-parameters

API。现在需要插入一条具有相关记录的记录。我读了嵌套属性,但没有任何想法。我无法理解。

我尝试在rails mvc项目中使用一个示例,但即使我无法在一对一映射本身中创建关联记录。请告诉我这样做的步骤或带样品的任何好文章?

无论如何以下是我的工作

我的模特是

class Instructor < ActiveRecord::Base
  has_one :office_assignment
  has_many :departments
  has_and_belongs_to_many :courses

  accepts_nested_attributes_for :office_assignment
end

class OfficeAssignment < ActiveRecord::Base
  belongs_to :instructor
end

我的创建控制器方法

def new
    @instructor = Instructor.new
  end

  def create
    @instructor = Instructor.new(instructor_params)

    respond_to do |format|
      if @instructor.save

        format.html { redirect_to @instructor, notice: 'Instructor was successfully created.' }
        format.json { render :show, status: :created, location: @instructor }
      else
        format.html { render :new }
        format.json { render json: @instructor.errors, status: :unprocessable_entity }
      end
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_instructor
      @instructor = Instructor.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def instructor_params
      params.require(:instructor).permit(:LastName, :FirstMidName, :HireDate, office_assignment_attributes: [:Location])
    end

我的创建表单

<%= form_for @instructor, :html => { :class => "form-horizontal instructor" } do |f| %>

    <% if @instructor.errors.any? %>
    <div id="error_expl" class="panel panel-danger">
      <div class="panel-heading">
        <h3 class="panel-title"><%= pluralize(@instructor.errors.count, "error") %> prohibited this instructor from being saved:</h3>
      </div>
      <div class="panel-body">
        <ul>
        <% @instructor.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
        </ul>
      </div>
    </div>
  <% end %>

  <div class="form-group">
    <%= f.label :LastName, :class => 'control-label' %>
    <div class="controls">
      <%= f.text_field :LastName, :class => 'form-control' %>
    </div>
    <%= error_span(@instructor[:LastName]) %>
  </div>
  <div class="form-group">
    <%= f.label :FirstMidName, :class => 'control-label' %>
    <div class="controls">
      <%= f.text_field :FirstMidName, :class => 'form-control' %>
    </div>
    <%= error_span(@instructor[:FirstMidName]) %>
  </div>
  <div class="form-group">
    <%= f.label :HireDate, :class => 'control-label' %>
    <div class="controls">
      <%= f.text_field :HireDate, :class => 'form-control' %>
    </div>
    <%= error_span(@instructor[:HireDate]) %>
  </div>

    <div class="form-group">
      <%= f.label :Location, :class => 'control-label' %>
      <div class="controls">
        <input type="text" name="office_assignment_Location" class ="form-control">
      </div>
      <%= error_span(@instructor[:HireDate]) %>
    </div>


  <%= f.submit nil, :class => 'btn btn-primary' %>
  <%= link_to t('.cancel', :default => t("helpers.links.cancel")),
            instructors_path, :class => 'btn btn-default' %>

<% end %>

请指导我..

修改

html文件中的更改

<%= f.fields_for :office_assignment_Location do |loc| %>
    <div class="form-group">
      <%= loc.label :Location, :class => 'control-label' %>
      <div class="controls">
        <%= loc.text_field :Location %>
      </div>
    </div>
    <%= loc.link_to_add "Add Location", :office_assignment_Location , :class=>'btn btn-primary'%>
<% end %>

我在控制器中的参数

def instructor_params
  params.require(:instructor).permit(:LastName, :FirstMidName, :HireDate, office_assignment_attributes: [:id, :Location ,:_destroy])
end

我的架构

create_table "instructors", force: :cascade do |t|
    t.string   "LastName",     limit: 255
    t.string   "FirstMidName", limit: 255
    t.date     "HireDate"
    t.datetime "created_at",               null: false
    t.datetime "updated_at",               null: false
  end

  create_table "office_assignments", primary_key: "Instructor_Id", force: :cascade do |t|
    t.string   "Location",   limit: 255
    t.datetime "created_at",             null: false
    t.datetime "updated_at",             null: false
  end

  add_foreign_key "office_assignments", "instructors", column: "Instructor_Id"

1 个答案:

答案 0 :(得分:0)

仅供参考:属性的名称应以小写字母而非资本开头。

以下是一些变化:

class Instructor < ActiveRecord::Base
  has_one :office_assignment , :dependent => :destroy # add dependent destroy
  has_many :departments
  has_and_belongs_to_many :courses

  accepts_nested_attributes_for :office_assignment,  :reject_if => :all_blank, :allow_destroy => true # add allow destroy
end

强参数的一些变化:

 def instructor_params
      params.require(:instructor).permit(:LastName, :FirstMidName, :HireDate, office_assignment_attributes: [:id, :Lesson ,:_destroy])
    end

注意:请勿忘记在:id

中添加:_destroyoffice_assignment_attributes

现在在View(form_template)中:

而不是:

<div class="form-group">
      <%= f.label :Location, :class => 'control-label' %>
      <div class="controls">
        <input type="text" name="office_assignment_Location" class ="form-control">
      </div>
      <%= error_span(@instructor[:HireDate]) %>
    </div>

应该是:

<%= nested_form_for @instructor, :html => { :class => "form-horizontal instructor" } do |f| %>

......
.....

<%= f.fields_for :office_assignment do |loc| %>
      <div class="form-group">
       <%= loc.label :Location, :class => 'control-label' %>
        <div class="controls"> 
          <%= loc.text_field :Location %>
        </div>
      </div>
    <% end %>
     <%= f.link_to_add "Add Location", :office_assignment , :class=>'btn btn-primary'%>

您必须像这样创建嵌套表单。我希望这会对你有所帮助。

注意:在表单中使用nested_form_for代替form_for: 供您参考: