以一对多关系将数组数据存储到数据库中

Storing array data into database in one to many relationship

大家好,我想给用户添加分支,我有这样的用户模型:

class User < ActiveRecord::Base
   has_many :user_branches
end  

然后我有这样的用户控制器:

def create
@user_branches=params[:branch_ids]

params[:user][:password] = params[:user][:username]
@user = User.new(params[:user])
respond_to do |format|
  if @user.save
    # UserBranch.new(branch_id: b[0], user_id: params[:user_id])
     @user_branches.each do |branch|
      @user_branch = UserBranch.new(branch_id: branch, user_id: params[:user_id])
     @user_branch.save
    end

    flash[:notice] = 'Success Add New User'
    format.js
  else
    flash[:error] = @user.errors.full_messages
    format.js#html { render action: "new" }
  end
end

@user_branches的内容是这样的["2", "3", "4"]。 以上代码工作。但是 user_id 没有插入。

params[:user_id] 你怎么能从 form 得到这个?

您正在 create 方法中创建 user

应该是,

UserBranch.new(branch_id: branch, user_id: @user.id)