ruby-on-rails – 嵌套表单没有出现!
发布时间:2020-12-17 03:27:51 所属栏目:百科 来源:网络整理
导读:我有一个嵌套的模型结构,如下所示: resources :users,:path = '/' do resources :accounts do resources :characters endend 我正在尝试获取帐户#new页面以显示两个表单但由于某种原因仅显示帐户表单(screenshot). 这是git:https://github.com/imjp/d2shed
我有一个嵌套的模型结构,如下所示:
resources :users,:path => '/' do resources :accounts do resources :characters end end 我正在尝试获取帐户#new页面以显示两个表单但由于某种原因仅显示帐户表单(screenshot). 这是git:https://github.com/imjp/d2shed account.rb class Account < ActiveRecord::Base attr_accessible :account_name,:realm accepts_nested_attributes_for :characters belongs_to :user has_many :characters,:dependent => :destroy validates :account_name,:presence => 'true',:length => { :in => 4..20 },:uniqueness => 'true' validates_presence_of :realm validates_format_of :account_name,:with => /^[A-Za-zd_]+$/ end accounts_controller.rb def new @user = User.find(params[:user_id]) @account = Account.new @account.characters.build end _form.html.erb <%= form_for([@user,@account]) do |f| %> <div class="field"> <%= f.label :account_name %><br /> <%= f.text_field :account_name %> </div> <div class="field"> <%= f.radio_button(:realm,"USWest") %> <%= f.label(:realm,"USWest") %> <%= f.radio_button(:realm,"USEast") %> <%= f.label(:realm,"USEast") %> <%= f.radio_button(:realm,"Europe") %> <%= f.label(:realm,"Europe") %> <%= f.radio_button(:realm,"Asia") %> <%= f.label(:realm,"Asia") %> </div> <%= f.fields_for :character do |character_form| %> <div class="field"> Name: <%= character_form.text_field :name %> </div> <% end %> <div class="actions"> <%= f.submit %> </div> <% end %> 编辑:代码现在工作! 解决方法
你为什么要做field_for“..”?
你想要做的是<%= f.fields_for:characters%>因为它将遍历所有字符并根据帐户表单中的要求呈现字段.通过调用f对象上的fields_for,您告诉父表单它包含嵌套属性. 其次,您需要在表单中使用@account对象,而不是使用@ user.accounts.build构建另一个对象.通过这种错误的方式,您实际上创建了一个新的帐户对象,该对象不会为其预先构建任何字符对象. 除此之外,您还需要在帐户模型中指定accepts_nested_attributes_for:字符,以便表单将其与帐户参数一起接受. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |