如果我在 application_controller
中:
def calendar_sidebar
@missed_dates_by_date = current_user.missed_dates.group_by {|i| i.date_missed.to_date} if current_user # I'm trying to call `missed_dates` method `date_missed`
@date = params[:date] ? Date.parse(params[:date]) : Date.today if current_user
end
我得到 undefined method 'missed_dates'
。
这是因为:
[1] pry(main)> MissedDate.last
id: 3,
user_id: nil,
我不知道如何使 user_id 不是 nil
,或者是否有其他方法可以解决这个问题。
MissedDate belongs_to :level
和 Level belongs_to :habit
和 Habit belongs_to :user
确实有一个 user_id
与之相关。
作为新手,我在脑海中想象这样的事情会奏效:
@missed_dates_by_date = current_user.habits.levels.date_missed.group_by {|i| i.date_missed.to_date}
但这给了 undefined method 'levels'
_calendar.html.erb
<%= calendar @date do |date| %>
<%= date.day %>
<ul>
<% @missed_dates_by_date[date].each do |missed_dates| %> # This is what I'm trying to get it to work for so that I can show in a calendar the date_missed
<%= missed_dates.date_missed %>
<% end %>
</ul>
<% end %>
最佳答案
要通过另一个关联获得一个关联,我们必须在模型中声明它并指定 :through
选项,像这样:
class User < ActiveRecord::Base
has_many :habits
has_many :levels, through: :habits
has_many :missed_dates, through: :levels
end
这样,ActiveRecord 就知道如何将错过的日期与用户相关联并可以自动检索它们(无需 MissedDate
上的 user_id
字段):
current_user.missed_dates.where(attribute: value)
您可能应该从 MissedDate
中删除 user_id
以避免与这样的迁移混淆:
def up
remove_column :missed_dates, :user_id
end
def down
# insert the code to re-create the column
end
关于ruby-on-rails - 如何使用 ApplicationController 的嵌套属性方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32637659/