[英]Writing scope for a has_many belongs_to Association - Rails 4
我是 Rails 的新手,因此非常感謝您的幫助和建議。
目的:
@user.forms.count
計算所有用戶申請表 - 這將顯示所有廣告的所有表單楷模
user.rb
has_many forms
form.rb
belongs_to user
belongs_to advert
advert.rb
has_may forms
scope :active_adverts, -> {where(['deadline >= ?', Date.current])}
用戶控制器.rb
def dashboard
if current_user
@user = User.find(current_user)
@user_applications = @user.forms
@form = @user.forms.find(params[:id])
else
redirect_to error_path
end
end
我在視圖“views/users/dashboard.html.erb” <%= @user.forms.where(advert: @form.advert.active_advert).count %>
嘗試了這個,但我開始意識到這不會工作。 您的建議將不勝感激
您可以像這樣定義scope
:
class User < ActiveRecord::Base
has_many :forms
has_many :adverts, through: :forms # <-- The change here
end
class Advert < ActiveRecord::Base
has_many :forms
scope :active, -> { where('deadline > ?', Time.now) } # <-- The change here
end
class Form < ActiveRecord::Base
belongs_to :user
belongs_to :advert
end
所以你的count function
將是:
@users.adverts.active.count
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.