0

アイテムの作成後にアイテムの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
4

3 に答える 3

0

最も簡単な修正は、update_attributesに渡す引数を修正することです。

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

その時点では、paramsハッシュにはその部分がありません。これには主に、フォームから取得したparams [:team]などのGET/POST変数からの情報が含まれています。

アップデート

モデルを確認した後、update_attributesはteam_idをアクセス可能にしないと機能しません。これはセキュリティの問題です。通常、外部キーをアクセス可能にしないでください。代わりに、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
于 2013-02-24T02:56:33.883 に答える
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 }

リダイレクト後ではなく、保存後に更新コードを使用します。

于 2013-02-24T03:59:47.657 に答える
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
于 2013-02-24T04:53:50.700 に答える