0

ユーザーコントローラーと通知コントローラーがあります。ユーザー has_many 多数の他のモデルによる通知。notifications#destroy アクションで @user を定義して、javascript で参照できるようにする良い方法はありますか?

私のユーザーショーページには、このようなものがあります。

ユーザー/show.html.erb

<div>

  <div id="user_notificationss_count">
    "You have <%= @user.notifications.count %> notifications"
  </div>

  <%= render @user.notifications %>

</div>

notifications/_notification.html.erb

  <div id="notification_<%= @notification.id %>">
    <div>Congrats, you have earned XXX badge!</div>
    <div><%= link_to 'X', notification, method: :delete, remote: true %></div>
  </div>   

users_controller.rb

def show
  @user = User.find(params[:id])
end

notifications_controller.rb

def destroy
  @notification= Notification.find(params[:id])
  @notification.destroy
  respond_to |format|
    format.html { redirect_to :back }
    format.js
  end
end

通知/destroy.js.erb

$("#notification_<%= @notification.id %>").remove();
$("#user_notifications_count").html("You have <%= @user.notifications.count %> notifications");

JavaScript では、最初の行は正常に.remove();動作します。ただし、コントローラーの破棄アクションで @user を定義していないため、2 行目は機能しません。私のユーザー モデルには、他の複数のモデルによる has_many 通知があります。したがって、各通知には特定の user_id はありません。レンダリングされている user#show ページから user_id パラメータを取得する方法はありますか?

はっきりしていない場合は申し訳ありません。お知らせください。追加の説明/コードで補足します。ありがとう!


編集:モデルコードの追加

user.rb

attr_accessible :name
has_many :articles
has_many :comments
has_many :badges

def notifications(reload=false)
  @notifications = nil if reload
  @notifications ||= Notification.where("article_id IN (?) OR comment_id IN (?) OR badge_id IN (?)", article_ids, comment_ids, badge_ids)
end

記事.rb

attr_accessible :content, :user_id
belongs_to :user
has_many :notifications

コメント.rb

attr_accessible :content, :user_id
belongs_to :user
has_many :notifications

Badge.rb

attr_accessible :name, :user_id
belongs_to :user
has_many :notifications

通知.rb

attr_accessible :article_id, :comment_id, badge_id
belongs_to :article
belongs_to :comment
belongs_to :badge
4

1 に答える 1

1

Notificationモデルに仮想属性を設定するとうまくいきます。

# app/models/notification.rb
class Notification < ActiveRecord::Base
    belongs_to :article, :comment, :badge

    def user
        if article_id.nil? && comment_id.nil?
            badge.user
        elsif comment_id.nil? && badge_id.nil?
            article.user
        elsif badge_id.nil? && article_id.nil?
            comment.user
        end
    end
end

destroy次に、通知コントローラーのアクションで親を検索できます。

# app/controllers/notifications_controller.rb
def destroy
    @notification= Notification.find(params[:id])
    @user = @notification.user
    ...
end

その後、上記のスニペット@userで示したように、インスタンス変数にアクセスできるようになります。destroy.js.erb

于 2013-06-15T23:21:16.023 に答える