我是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])}
users_controller.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 %>
视图中尝试了此操作,但我发现这样做无效。你的建议将不胜感激
答案 0 :(得分:1)
您可以像这样定义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