ruby-on-rails Rails -如何从模型中查询has_many

7uhlpewt  于 2022-12-24  发布在  Ruby
关注(0)|答案(1)|浏览(238)
    • bounty将在7天后过期**。回答此问题的人有资格获得+50的声望奖励。spacerobot希望吸引更多人关注此问题。

我有一个scheduleevent模型。这个模型使用ice_cube来创建重复规则。一个scheduleevent有_many个schedtimeranges。一个schedtimeranges有一个start_time,end_time和一周中星期日到星期六的布尔值。无论哪一天被选中都是真的。
我需要做的是把这些日子放到一个数组中传递给ice_cube。我如何将scheduleevent连接到schedtimeranges,并在Rails模型中得到值为true的Sunday-Saturday?我是在控制器中查询记录,然后在模型中循环它们,还是如果我需要在模型中循环,从模型中查询它们?
尝试执行类似这样的操作,但收到无方法schedtimeranges错误:

def self.timeranges
    Schedtimeranges.where(scheduleevent_id: self.id).columns.select{ |c| c.type == :boolean }.map(&:name)
  end
  weekdays = self.timeranges

计划事件模型:

has_many :schedtimeranges, inverse_of: :scheduleevent
  accepts_nested_attributes_for :schedtimeranges, allow_destroy: true

编辑:

weekdays = schedtimeranges.where(scheduleevent_id: id).columns.select{ |c| c.type == :boolean }.map(&:name).to_a

这是可行的,但是我只需要在值为真的地方得到它们,我怎么把它加到这个里面呢?所以如果一个scheduleevent有3个schedtimeranges,我想在它们为真的地方得到一周中的几天,以及start_time/end_time。
预期输出为07:00AM,14:00PM,星期一,星期四,星期五。(如果这三天为真。

create_table "schedtimeranges", force: :cascade do |t|
    t.bigint "scheduleevent_id", null: false
    t.string "start_time"
    t.string "end_time"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.boolean "monday"
    t.boolean "tuesday"
    t.boolean "wednesday"
    t.boolean "thursday"
    t.boolean "friday"
    t.boolean "saturday"
    t.boolean "sunday"
    t.index ["scheduleevent_id"], name: "index_schedtimeranges_on_scheduleevent_id"
  end
yhived7q

yhived7q1#

我认为你把它说得比实际要复杂得多。预期输出帮助很大。我在Schedtimerange中添加了几个方法来简化它:

# why not ScheduleTimeRange and ScheduleEvent

class Schedtimerange < ApplicationRecord
  # sometimes you just have to type all the attributes that you need
  def days
    {
      monday:    monday,
      tuesday:   tuesday,
      wednesday: wednesday,
      thursday:  thursday,
      friday:    friday,
      saturday:  saturday,
      sunday:    sunday
    }
  end

  # # or like this
  # DAYS = %w[monday tuesday wednesday thursday friday saturday sunday].freeze
  # def days
  #   attributes.slice(*DAYS)
  # end

  # desired format goes here
  def to_ice_cube
    [start_time, end_time, *days.compact_blank.keys]
  end
end
  • https://api.rubyonrails.org/classes/Hash.html#method-i-compact_blank-21*
>> Schedtimerange.first.to_ice_cube
=> ["07:00 AM", "08:00 AM", :monday, :friday]

>> Schedtimerange.where(scheduleevent_id: 1).map(&:to_ice_cube)
=> [["07:00 AM", "08:00 AM", :monday, :friday], ["11:00 AM", "04:00 PM", :monday, :tuesday]]

如果需要,请对Scheduleevent执行相同的操作:
一个二个一个一个

相关问题