Hướng dẫn sử dụng class Support trong model
Bài đăng này đã không được cập nhật trong 10 năm
Trong coding standard của Framgia có quy định rõ việc chia sẻ các biến instance trong controller: "Không chia sẻ giữa controller và view từ 2 biến instance trở lên"
Làm thế nào để có thể truyền nhiều biến instance từ controller qua view?
Trong trường hợp bạn muốn share từ 3 biến instance trở lên, ví dụ, cần truyền các biến sau từ UsersController qua view:
def show
@book_favorites = book_favorites
@book_reads = book_reads
@book_readings = book_readings
end
Để giải quyết vấn đề này chúng ta sẽ giải quyết như sau:
- Tạo class UserSupport trong thư mục: models/supports.
class Supports::UserSupport
attr_reader :user
def initialize user
@user = user
end
def reads
@user.reads
end
def readings
@user.readings
end
def favorites
@user.favorites
end
end
(Trong class này bạn định nghĩa các method để lấy dữ liệu.)
- Trong UsersController chỉ cần khao báo như sau:
@support = Support::UserSupport.new(@user)
3.Lấy lại dữ liệu trong users/show.html.erb
<%= render partial: "book_status/book_status",
collection: @support.favorites, as: :book_status %>
<%= render partial: "book_status/book_status",
collection: @support.reads, as: :book_status %>
<%= render partial: "book_status/book_status",
collection: @support.readings, as: :book_status %>
Chi tiết tham khảo tại: https://github.com/framgia/brs_34/pull/11
All rights reserved