Hỏi về kế thừa trong controller Rails
Class ActivityNotification::NotificationsController kế thừa ActivityNotification.config.parent_controller.constantize
https://github.com/simukappu/activity_notification/blob/master/app/controllers/activity_notification/notifications_controller.rb#L3
ActivityNotification.config.parent_controller có giá trị default là ApplicationController
https://github.com/simukappu/activity_notification/blob/master/lib/activity_notification/config.rb#L159
Nếu bạn muốn thay đổi parent class này thì bạn có thể config trong initializer mà gem này tạo ra
config/initializers/activity_notification.rb
ActivityNotification.configure do |config|
...
config.parent_controller = 'BaseController'
...
end
Khi đó thì bạn sẽ có quan hệ
NotificationsController < ActivityNotification::NotificationsController < BaseController
Rails - Activity Log lấy thông tin đối tượng bị tác động?
Em có thể thêm 1 cột để lưu type của đối đượng vào trong bảng activities. Và nếu đã làm vậy thì anh nghĩ em nên dùng tính năng Polymorphic Associations của Rails.
Giả sử bảng activities mới có cấu trúc và nội dung như này (anh dùng target_id thay cho affected_id)
| id | user_id | target_id | target_type |
|---|---|---|---|
| 1 | 1 | 1 | Post |
| 2 | 1 | 1 | Photo |
Lưu ý: target_type là dạng String và chứa tên các model Post hoặc Photo.
Trong model Activity định nghĩa association target như này
class Activity < ApplicationRecord
belongs_to :target, polymorphic: true
end
thì khi gọi activity.target nó sẽ tự động trả về object của class Post hoặc Photo tuỳ thuộc vào giá trị của activity.target_type.
Với dữ liệu trong bảng trên thì
Activity.first.target # => trả ra Post object với id = 1
Activity.second.target # => trả ra Photo object với id = 1
Mặt khác, khi tạo activity mới chỉ cần gọi
user = User.find(...)
post = Post.find(...)
Activity.create user: user, target: post
thì các giá trị target_id và target_type cũng sẽ được tự động set.
Tổ chức
Chưa có tổ chức nào.