ruby-on-rails - 如何使用 ApplicationController 的嵌套属性方法?

标签 ruby-on-rails ruby model-view-controller

如果我在 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/

相关文章:

C# - 将 UI 与业务代码分开

vb.net - 使用 VB.Net 的 NerdDinner 验证问题

php - 使用自定义 PHP MVC 在另一个 foreach 循环中进行 foreach 循环

ruby-on-rails - 如何从 Jquery Ajax 获取数据

sql - 在查询的选择中传递参数

mysql - rails : Insert a lot of HTML code through migration to the database

ruby - 尽早突破开始/结束 block

ruby-on-rails - 在 Ruby on Rails 开发中使用 Cucumber 传递 autospec 中的选项

ruby-on-rails - Heroku 部署 - 无法加载此类文件 - rake (LoadError)

ruby - 如何在 Ruby 中使用模块覆盖静态类方法?