0

新しいサイト レコードを作成するときに、many_to_many テーブルを更新することができません。sites テーブルは更新されますが、sites_users は更新されません。サイトの作成時に、user_id と site_id が sites_users テーブルに追加されることを期待しています。

私の移行:

class CreateTableSiteUser < ActiveRecord::Migration
def up
  create_table :sites_users, :id => false do |t|
      t.integer :site_id
      t.integer :user_id
  end

モデル:

user.rb

class User < ActiveRecord::Base
attr_accessible  :name, :email, :password, :password_confirmation, :user_id
has_secure_password
has_and_belongs_to_many :sites

サイト.rb

class Site < ActiveRecord::Base
attr_accessible :name, :site_key, :organization_id, :user_id, :site_id
belongs_to :organization
has_and_belongs_to_many :users

sites_controller.rb

def create
  @site = Site.new(params[:site])
    @site.organization_id = Organization.where(:user_id => current_user.id)
    @user_id = current_user.id
    if @site.save
        flash[:success] = "New Site Created!"
        redirect_to root_path
    else

site_id と user_id を取得して、sites_users 結合テーブルに保存するには、他に何が必要ですか?

私は多対多についてできるだけ多くのことを読み、多くのスルートピックを投稿し、Railscast ビデオを見て、できる限り検索しました。どんな助けでも大歓迎です。

ありがとう!

4

1 に答える 1

1

アクションで新しいサイトを作成していてcreate、そのサイトを に割り当てたい場合current_userは、次のことを試してください。

if @site.save
  @site.users << current_user
  flash[:success] = "New Site Created!"
  redirect_to root_path
else
  ...

current_userこれはユーザーのリストに追加されますが、検証に合格して保存され@siteた後にのみ追加されます。@site

于 2013-04-05T00:10:31.710 に答える