我正在尝试找出在创建项目后获取项目 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