嵌套表单不在Rails中显示

时间:2014-07-07 23:15:23

标签: ruby-on-rails ruby activerecord nested-attributes

我有一个名为isp的模型表单,其中'has_many'是isp帐户。 isp帐户属于'isp'。

对isp_account进行验证意味着如果没有isp_id则无法添加,所以我的理由是创建一个嵌套表单。我创建了嵌套表单,如此

= simple_form_for @isp, :html => { :multipart => true } do |f|
  = f.input :title
  = f.simple_fields_for :isp_accounts do |tag|
    = tag.input :title, label: "Tag Name"

但是没有显示嵌套属性。没有错误等等。这是为什么?我是以最好的方式接近这个吗?这是唯一的方法吗?

这是代码

ISP模型

class Isp < ActiveRecord::Base
  has_many :isp_accounts, dependent: :destroy
  has_many :deployments, through: :servers
  has_many :servers, through: :isp_accounts
  validates :title, presence: true

  accepts_nested_attributes_for :isp_accounts


end

ISP账户模型

class IspAccount < ActiveRecord::Base

  belongs_to :isp
  has_many :deployments, through: :servers
  has_many :servers, dependent: :destroy

  validates :title, presence: true
  validate :check_associates

  private

  def check_associates
    associated_object_exists Isp, :isp_id
  end
end

ISP帐户控制器

    ....
    def new
        @isp_account = IspAccount.new
    end

    def update
    @isp_account.update_attributes(isp_accounts_path)
    if @isp_account.save
      record_saved
      return redirect_to(isp_accounts_path)
    else
      check_for_errors
      return render('/isp_accounts/edit')
    end
  end

    private

    def get_isp_accounts
        @isp_account = IspAccount.all
    end

    def get_isp_account
        @isp_account = IspAccount.find(params_isp_accounts)
    end
    def params_isp_accounts
    params.require(:isp_account).permit!
  end
end

....
  def new
    @isp = Isp.new
  end

  def update
    @isp.update_attributes(params_isp)
    if @isp.save
      record_saved
      return redirect_to(isps_path)
    else
      check_for_errors
      return render('new')
    end
  end

  private 

  def params_isp
    params.require(:isp).permit(:title, isp_accounts_attributes: [:id, :title])
  end

  def get_isp
    @isp = Isp.where(id: params[:id]).first
    unless @isp
      record_not_found
      return redirect_to(isps_path)
    end
  end

  def get_isps
    @isp = Isp.all.order(:title)
  end
end

SCHEMA

create_table "isp_accounts", force: true do |t|
    t.string   "title"
    t.integer  "isp_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "isps", force: true do |t|
    t.string   "title"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

1 个答案:

答案 0 :(得分:0)

好吧,我明白了。我错过了控制器中该属性的新位。非常基本的。

def new
   @isp = Isp.new
   @isp.isp_accounts.new
 end