ユーザーコントローラーと通知コントローラーがあります。ユーザー 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