3

次のように、2 つのモデル間に多対多の関係があります。

#users.rb
has_many :users_to_roles
has_many :roles, through: :users_to_roles

#users_to_roles.rb
belongs_to :user
belongs_to :role

#roles.rb
has_many :users_to_roles
has_many :users, through: :users_to_roles

「このロールにいる」ユーザーがいる場合、ロールの削除を無効にしたい。ここで、作業を行うべき 2 つのオプションを見つけました。

:restrict_with_exception は、関連付けられたレコードがある場合に例外を発生させます :restrict_with_error は、関連付けられたオブジェクトがある場合に所有者にエラーを追加します

しかし、これの構文とそれがどのように機能するかの例はありません。

これを有効にするのを手伝ってもらえますか:

#roles.rb
has_many :users_to_roles
has_many :users, through: :users_to_roles, dependent: restrict_with_exception
4

4 に答える 4

2

または、コントローラーで例外をレスキューすることもできます。この例では、連絡先が関心を持っている可能性があります。つまり、

  class Interest < ActiveRecord::Base
    belongs_to :contact
  end

  class Contact < ActiveRecord::Base
    has_many :interests, :dependent => :restrict
   end

次に、コントローラーで:

def destroy
    @contact = Contact.find(params[:id])
    begin
        @contact.destroy
    rescue
        flash[:msg] = "Can't delete - owns interest"
    end

   respond_to do |format|
      format.html { redirect_to(:back) }
      format.xml  { head :ok }
    end
end

呼び出しページにフラッシュ メッセージが表示されます。

于 2014-08-05T18:59:35.967 に答える
0

Railsの正しい方法は、次のようにすることです。

ユーザー.rb:

has_many :users_to_roles, dependant: :destroy # don't keep the join table entry if the user is gone
has_many :roles, through: :users_to_roles

結合に冗長なエントリ (いずれかの列が null または孤立している) がないことを確認してください。

users_to_roles.rb:

belongs_to :user
belongs_to :role

# add validations presence of both user and role
# in both model and database.

ボーナス、レール 4.2 から、参照整合性forigen_key: trueのために移行に追加できます

今あなたの役割で(私はあなたがあなたのモデルに単独で名前を付け、質問でタイプミスをしたと仮定しています)、これを追加します:

役割.rb:

has_many :users_to_roles, dependant: :restrict_with_error
has_many :users, through: :users_to_roles
于 2016-06-08T11:30:07.610 に答える