创建到另一个表后插入ID

时间:2013-02-24 02:48:07

标签: ruby-on-rails activerecord

我正在尝试找出在创建项目后获取项目ID的最佳方法,并将该ID传递到另一个表中。即用户创建一个保存在团队数据库中的团队,我想将team_id分配到我的用户表中。

我已经尝试了以下但没有成功

    def create
    @team = Team.new(params[:team])
    @user = current_user
    respond_to do |format|
      if @team.save
        format.html { redirect_to(teams_url,
                                  :notice => "Team #{@team.name} was successfully created.") }
        format.json { render :json => @team, :status => :created, :location => @team }
        @user.update_attributes(params[:user][@team.id])
      else
        format.html { render :action => "new" }
        format.json { render :json => @team.errors, :status => :unprocessable_entity }
      end
    end
  end

团队模型

class Team < ActiveRecord::Base
  has_many  :users
  has_many  :events
  belongs_to :division
  belongs_to :sport
  attr_accessible :name, :division_id, :sport_id
  validates :name, :presence => true

end

用户模型

class User < ActiveRecord::Base


devise :database_authenticatable, :registerable, :confirmable,
         :recoverable, :rememberable, :trackable, :validatable, :omniauthable

  belongs_to :sport
  belongs_to :team
  has_many :availabilities

执行sql

    Started POST "/teams" for 127.0.0.1 at 2013-02-24 15:24:40 +1100
Processing by TeamsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"ztr8E+jg3hCe3cQoDefS3Rw5GQJGZfHsffffbCZiGRs=", "team"=>{"sport_id"=>"19", "division_id"=>"", "name"=>"test"}, "commit"=>"Create Team"}
  User Load (2.1ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
  User Load (3.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]
   (0.2ms)  BEGIN
  SQL (0.9ms)  INSERT INTO "teams" ("created_at", "division_id", "name", "sport_id", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["created_at", Sun, 24 Feb 2013 15:24:40 EST +11:00], ["division_id", nil], ["name", "test"], ["sport_id", 19], ["updated_at", Sun, 24 Feb 2013 15:24:40 EST +11:00]]
   (1.7ms)  COMMIT
   (0.2ms)  BEGIN
   (0.4ms)  ROLLBACK
Redirected to http://localhost:3000/teams

3 个答案:

答案 0 :(得分:0)

最简单的解决方法是修复传递给update_attributes

的参数
@user.update_attributes(:team_id => @team.id)

params hash在那一点上没有参与其中。它主要包含来自GET / POST变量的信息,例如来自您表单的params [:team]。

<强>更新

在看到你的模型之后,如果没有使team_id可访问,update_attributes将无法工作,这是一个安全问题,通常不应该访问外键。而是使用赋值替换update_attributes。

def create
  @team = Team.new(params[:team])
  respond_to do |format|
    if @team.save
      format.html { redirect_to(teams_url, :notice => "Team #{@team.name} was successfully created.") }
      format.json { render :json => @team, :status => :created, :location => @team }
      # use assignment instead to avoid mass assignment errors
      current_user.team = @team
    else
      format.html { render :action => "new" }
      format.json { render :json => @team.errors, :status => :unprocessable_entity }
    end
  end
end

答案 1 :(得分:0)

应使用活动记录关联解决此问题。 http://guides.rubyonrails.org/association_basics.html
这是将一个项ID转换为另一个不同数据库项的最佳方法。所以尝试使用活动记录关联。
更新

    if @team.save
    @user.update_attributes(:team_id => @team.id)
    format.html { redirect_to(teams_url,
                                  :notice => "Team #{@team.name} was successfully created.") }
   format.json { render :json => @team, :status => :created, :location => @team }

重定向后保存后使用更新代码。

答案 2 :(得分:0)

以下3个选项

def create
  @team = Team.new(params[:team])
  saved = false

  Team.transaction do
    saved = @team.save
    if saved
      # 1) this should work ?
      @team.users << current_user
      # 2) if that doesn't then this most def
      current_user.team = @team
      current_user.save!
      # 3) or 
      current_user.update_attribute(:team_id, @team.id)
    end
  end

  respond_to do |format|
    if saved        
      format.html { redirect_to(teams_url, :notice => "Team #{@team.name} was successfully created.") }
      format.json { render :json => @team, :status => :created, :location => @team }        
    else
      format.html { render :action => "new" }
      format.json { render :json => @team.errors, :status => :unprocessable_entity }
    end
  end     
end