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

时间:2015-11-05 09:16:04

标签: ruby-on-rails associations one-to-many

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

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没有插入。

1 个答案:

答案 0 :(得分:0)

function success(position) { $.ajax({ url: 'https://api.forecast.io/forecast/<apikey>/' + position.coords.latitude + "," + position.coords.longitude + "?units=si", jsonp:'callback', dataType:'jsonp', success:function(data){ (stuff...) } }); } function failure() { console.warn('Error('+err.code+'):'+err.message); } navigator.geolocation.getCurrentPosition(success, failure); 你怎么能从params[:user_id]得到这个?

您正在form方法中创建user

应该是,

create