首页 > 代码库 > Rails accepts_nested_attributes_for表单嵌套的利器
Rails accepts_nested_attributes_for表单嵌套的利器
http://blog.csdn.net/kunshan_shenbin/article/details/7249713http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-fields_forhttp://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#method-i-accepts_nested_attributes_for
还在为表单嵌套而苦恼么,看看accepts_nested_attributes_for方法吧,今天在项目里用过之后,更爱这门语言了.
# eoncoding: UTF-8class Package include Mongoid::Document include Mongoid::Timestamps include ImageUploadable store_in collection: ‘all_apps‘ field :language, type: String, default: ‘中文‘ field :url, as: :download_url, type: String //as别名 field :intro_icons, type: Array, default: [] field :updated_on, type: Date field :is_actived, type: Boolean, default: false field :position, type: Integer, default: 0 field :is_deleted, type: Boolean, default: false index code: 1 //索引 index package: 1 has_many :recommend_apps, foreign_key: ‘app_id‘ accepts_nested_attributes_for :recommend_apps
class RecommendApp include Mongoid::Document include Mongoid::Timestamps include ImageUploadable validates :app_id, presence: true validates :type, inclusion: { in: TYPES.keys } validates :app_id, uniqueness: { scope: :type } belongs_to :package, foreign_key: ‘app_id‘
<%= form_for @recommend_app, html: { class: package_form_class(@recommend_app), role: ‘form‘ } do |f| %> <div class="form-group"> <%= f.label :position, "推荐位置", class: "col-sm-2 control-label" %> <div class="col-sm-3"> <%= f.text_field :position,:class =>"form-control" %> </div> </div> <%= fields_for :package do |package| %> <div class="form-group"> <%= package.label :title, "名称", class: "col-sm-2 control-label" %> <div class="col-sm-3"> <%= package.text_field :title ,:class =>"form-control" %> </div> </div> <% end %>
recommend_apps_controller.rb
def edit @package = @recommend_app.package end def update old_position = @recommend_app.position if @recommend_app.update_attributes recommend_app_params @package = @recommend_app.package if @package.update_attributes package_params @recommend_app.adjust_recommend_app_position(@recommend_app.position) redirect_to recommend_apps_path, notice: ‘操作成功‘ end else render :edit end end
fields_for(record_name, record_object = nil, fields_options = {}, &block)
可以看下下面的文档
http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-fields_for
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。