父模型id不通过,使用ryan bates嵌套表单

时间:2013-12-19 08:02:08

标签: ruby-on-rails nested-forms

我正在尝试使用Ryan Bates优秀的'嵌套表单'来创建以下内容 - >

创建新的“作业”时,用户可以选择写入多个关于它的项目符号,以及多个“角色”

以下是模型的设置方法:

工作模式

# == Schema Information
#
# Table name: jobs
#
#  id             :integer          not null, primary key
#  job_title      :string(255)
#  job_summary    :string(255)
#  qualifications :string(255)
#  created_at     :datetime
#  updated_at     :datetime
#

class Job < ActiveRecord::Base
    validates :job_title, presence: true 
    validates :job_summary, presence: true
    validates :qualifications, presence: true 

    has_many :bullets, dependent: :destroy 
    has_many :roles, dependent: :destroy

    accepts_nested_attributes_for :bullets, :reject_if => lambda { |a| a[:bullet].blank? }, :allow_destroy => true
    accepts_nested_attributes_for :roles, :reject_if => lambda { |a| a[:role_title].blank? }, :allow_destroy => true
        #lambda { |a| a[:bullet].blank? } makes sure that on edit, if a value is left blank, then it doesn't save it

end

子弹模型

# == Schema Information
#
# Table name: bullets
#
#  id         :integer          not null, primary key
#  job_id     :integer
#  bullet     :string(255)
#  created_at :datetime
#  updated_at :datetime
#

class Bullet < ActiveRecord::Base
    belongs_to :job
    validates :job_id, presence: true
    validates :bullet, presence: true
end

角色模型

# == Schema Information
#
# Table name: roles
#
#  id         :integer          not null, primary key
#  job_id     :integer
#  role_title :string(255)
#  role_desc  :string(255)
#  created_at :datetime
#  updated_at :datetime
#

class Role < ActiveRecord::Base
    belongs_to :job

    validates :job_id, presence: true
    validates :role_title, presence: true
    validates :role_desc,  presence: true
end

职位控制人员:

class JobsController < ApplicationController
  before_action :signed_in_user, only: [:new, :create, :update, :show, :edit, :destroy] # index, at least partially is available to all viewers
  before_action :admin_user, only: [:new, :edit, :update, :create, :destroy] # only admins can make jobs

  def new 
    @job = Job.new
    3.times {
        @job.bullets.build
        @job.roles.build
    }
  end

  def create
     @job = Job.new(job_params)
     if @job.save
       redirect_to root_path, :flash => { :success => "Job created!" }
     else
       render 'new'
     end
  end

  def job_params 
    params.require(:job).permit(:job_title, :job_summary, :qualifications,
                                 bullets_attributes: [:id, :bullet, :_destroy],
                                 roles_attributes: [:id, :role_title,:role_desc, :_destroy])
  end

end

工作/新视图

<% provide(:title, "Publish a new job") %>
<%= nested_form_for @job do |f| %>
  <%= render 'shared/error_messages', object: f.object %>

  <%= f.label :job_title %>
  <%= f.text_field :job_title %>

  <div style="margin-left:30px">
      <%= f.fields_for :bullets do |bullet_form| %>
        <%= bullet_form.label :bullet %>
        <%= bullet_form.text_field :bullet %>
        <%= bullet_form.link_to_remove "Remove this bullet" %>
      <% end %>
      <p><%= f.link_to_add "Add a Bullet", :bullets %></p>
  </div>


  <%= f.label :job_summary %>
  <%= f.text_area :job_summary %>

  <%= f.label :qualifications %>
  <%= f.text_area :qualifications %>

  <div style="margin-left:30px">
      <%= f.fields_for :roles do |role_form| %>
        <%= role_form.label :role_title %>
        <%= role_form.text_field :role_title %>
        <%= role_form.label :role_desc %>
        <%= role_form.text_field :role_desc %>
        <%= role_form.link_to_remove "Remove this Role" %>
      <% end %>
      <p><%= f.link_to_add "Add a Role", :roles %></p>
  </div>



  <%= f.submit "Publish the Job", class: "button" %>
<% end %>
唉,看起来我做错了。当我尝试创建新作业时,我收到错误:

* Bullets job can't be blank
* Roles job can't be blank

在我看来,job_id的信息并没有通过嵌套表单。

您的想法正在发生,并且非常感谢有关完成这项工作的想法:)

日志

以下是一些日志,以使其更清晰:

1)当我提交表单时,只选择1个项目符号,我在开发中得到以下参数:

 --- !ruby/hash:ActionController::Parameters
utf8: ✓
authenticity_token: ezgktBZjcrdI6nMTro8Aqd0Djs2k3M+HFAdACrxajS8=
job: !ruby/hash:ActionController::Parameters
  job_title: Job Title example
  bullets_attributes: !ruby/hash:ActionController::Parameters
    '0': !ruby/hash:ActiveSupport::HashWithIndifferentAccess
      bullet: Example bullet
      _destroy: 'false'
  job_summary: Job Summary Example
  qualifications: Example Qualifications here
  roles_attributes: !ruby/hash:ActionController::Parameters
    '1387448871560': !ruby/hash:ActiveSupport::HashWithIndifferentAccess
      role_title: Example Role Name
      role_desc: Example Role Description
      _destroy: 'false'
commit: Publish the Job
action: create
controller: jobs

在我的Rails服务器上,这就是它所说的 - &gt;

Started POST "/jobs" for 127.0.0.1 at 2013-12-19 14:28:01 +0400
Processing by JobsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"ezgktBZjcrdI6nMTro8Aqd0Djs2k3M+HFAdACrxajS8=", "job"=>{"job_title"=>"Job Title example", "bullets_attributes"=>{"0"=>{"bullet"=>"Example bullet", "_destroy"=>"false"}}, "job_summary"=>"Job Summary Example", "qualifications"=>"Example Qualifications here", "roles_attributes"=>{"1387448871560"=>{"role_title"=>"Example Role Name", "role_desc"=>"Example Role Description", "_destroy"=>"false"}}}, "commit"=>"Publish the Job"}
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."remember_token" = '449addc616f3035c031b3220404a4d5eb5351c74' LIMIT 1
   (0.2ms)  begin transaction
   (0.2ms)  rollback transaction
  Rendered shared/_error_messages.html.erb (2.4ms)
  Rendered jobs/new.html.erb within layouts/application (15.7ms)
  Rendered layouts/_shim.html.erb (0.1ms)
  Rendered layouts/_header.html.erb (1.3ms)
Completed 200 OK in 101ms (Views: 32.0ms | ActiveRecord: 0.7ms | Solr: 0.0ms)

1 个答案:

答案 0 :(得分:1)

根据您发布的内容,有几个问题可能导致问题


强大的参数

def job_params 
    params.require(:job).permit(:job_title, :job_summary, :qualifications,
                                 bullets_attributes: [:bullet],
                                 roles_attributes: [:role_title,:role_desc])
end

我不知道您为何调用了列role_titlerole_desc,但最好只按实际名称调用列(title和{{1} })

这基本上是因为如果你加载desc,那么写@role而不是@role.title会更有效率。你的其他表也一样

您可能希望更新您的架构以反映


ActiveRecord Build

第二个问题是你正在构建新的ActiveRecord对象3次:

@role.role_title

如果您想发送3个对象,但是您只有1个,那就没关系了。我知道您已经完成了它,所以您可以添加额外的字段(我会在一秒钟内解释)

你应该改为:

 def new 
    @job = Job.new
    3.times {
        @job.bullets.build
        @job.roles.build
    }
 end

我认为这实际上是你的主要问题 - 如果你构建对象&amp;它们没有填充,它们是空白的,不是吗?

我只会声明我想要显示的对象,并在需要时添加额外内容


添加字段

如果您希望动态添加字段(使用Ajax),我强烈推荐this tutorial。它使用与Ryan Bates的方法相同的原理,但是更加清洁&amp;在需要时添加对象。如果你愿意,我可以通过聊天来讨论这个问题