문제

I'm trying to generate a scaffold for a single model object. The model object has several string properties and a few booleans. As part of my model, I need a property that's an array of hashes. Each hash represents a day of the week, along with a start time, and an end time. As JSON, here's what my object would look like:

{
  Name: "John Doe",
  Dept: "Health",
  Office Hours: [
    {
      Day: "Tuesday",
      Start: "10:00AM",
      End: "2:00PM"
    }, 
    { ... }
  isAdjunct: true
}

I have no idea how I'd create this. I'm obviously new to Rails, and I'm just trying to put something together quickly.

What's the best way to scaffold this sort of data model? Do I need two ActiveRecord classes? Am I missing some crucial information?

도움이 되었습니까?

해결책

Yes, you probably want two data models; say, Person and OfficeTime (you may think of better names!); then tie them together like this:

class Person < ActiveRecord::Base
  # name, dept, adjunct?
  has_many :office_times
end

class OfficeTime < ActiveRecord::Base
  # day, start, end
  belongs_to :person # database has a person_id field
end

Have a look at the Rails Guides chapter on Relations for more guidance.

다른 팁

Just to get you started, I thing you need two models; Person and Availability with Person has_may availabilities (watch out for the default pluralization) and Availabilty belongs_to person.

Use association.........

create a migration or use rails g migration add_person_id_to_hours person_id:integer

 class Person < ActiveRecord::Base
    has_many :hours
   end

  class Hours < ActiveRecord::Base
    belongs_to :person 
  end
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top