Rails中嵌套表单的解决:模型关系是一对一和一对多的情况

一、什么是嵌套表单呢?

    举个简单的例子吧,比如你有两个表,一个User表,另一个Profile表,他们是一对一的关系(也可以一对多等)。现在需要提交一个表单的时候同时提交User,Profile对应的字段数据。在Rails中有一种简单的方法解决,分别使用了这些方法

accepts_nested_attributes_for 
attr_accessible
fields_for

下面我们用代码进行说明一下。针对模型关系是一对一

class User < ActiveRecord::Base
   has_one :profile, dependent: :destroy
   accepts_nested_attributes_for :profile  #注意添加这两行
   attr_accessible  :profile_attributes #如果user_parms指定了,可以不加这行end
class Profile<ActiveRecord::Base
  belongs_to :user
end
class UsersController < ApplicationController
  def new
    @user = User.new
    @user.build_profile #不要遗漏,需要区别于一对多的情况
  end

 def create
     @user = User.new user_params
     if @user.save
       ...         
     end
  end
  
  private

  def user_params
    params.require(:user).permit(:password, :phone, :sms_token, profile_attributes: [:username])
  end
end

view中,users/new.html.erb:

 <% form_for @user do |f| %>
    <%= f.text_field :name %>
    <% f.fields_for :profile do |profile_form| %> #注意这里
      <%= profile_form.text_field :username %>
    <% end %>
 <% end %>

这是一对一的情况,假设是一对多呢:

在has_many中:User#@user.profiles.build,视图里面的profile,以及user_params里面的

profile_attributes要改成profiles_attributes

在has_one中:User#build_profile

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值