问题
I have the following Model...
class Room < ActiveRecord::Base
belongs_to :hotel
belongs_to :layout
has_many :visits
validates :number, presence: true
validates :rate, presence: true
validates :smoking, presence: true
def self.rooms_with_smoking(smoking)
self.where('smoking = ?', smoking)
end
def self.occupied_rooms(from_date, to_date) #24-26
self.joins(:visits).where('date >= ? and date <= ?', from_date, to_date).uniq
end
def self.vacant_rooms(from_date, to_date)
self.where.not(id: Room.occupied_rooms(from_date, to_date))
end
def self.blahblah(occupancy_count, smoking, from_date, to_date)
layouts = Layout.layouts_with_occupancy_count_gt(occupancy_count)
Room.rooms_with_smoking(smoking).vacant_rooms(from_date, to_date).joins(layouts)
end
end
The blahblah method...
When I attempt to run this from irb I get an error... "unknown class: Layout"
1) Does Room not 'know' about Layout. Can I not use another Model like this? How can I do it.
2) Theory question: Is it better to have one large method definition to obtain some information... or is it better to have a lot of little compartmentalized methods, and use them all in one method to obtain a larger piece of data. For example...
One 'Large' Method:
def self.find_rooms_with(occupancy_count, smoking, from_date, to_date)
Room.vacant_rooms(from_date, to_date).joins(:layout).where('occupancy_count >= ?', occupancy_count).where('smoking = ?', smoking)
end
By no means large, but everything is re-coded. Doesn't seem like it would follow DRY for long.
Many Little Methods:
def self.blahblah(occupancy_count, smoking, from_date, to_date)
layouts = Layout.layouts_with_occupancy_count_gt(occupancy_count)
Room.rooms_with_smoking(smoking).vacant_rooms(from_date, to_date).joins(layouts)
end
The second one is easier to code. It utilizes 3 built in method definitions. However, does it have any sort of performance hit over the first one, or is it less desirable?
EDIT: Answering the first two comments below...
When I just type Layout, or ap Layout, I get my entire Layout model.
class Layout < ActiveRecord::Base {
:id => :integer,
:description => :string,
:occupancy_count => :integer,
:created_at => :datetime,
:updated_at => :datetime
}
=> nil
And by irb, yes I mean rails console. Full Layout Model here...
class Layout < ActiveRecord::Base
has_many :rooms
validates :description, presence: true
validates :occupancy_count, presence: true
def self.layouts_with_occupancy_count(occupancy_count)
self.where('occupancy_count = ?', occupancy_count)
end
def self.layouts_with_occupancy_count_gt(occupancy_count)
self.where('occupancy_count >= ?', occupancy_count)
end
end
回答1:
1) It seems you do not declare the Layout class.
The belongs_to
class method expects a corresponding ActiveRecord class to be defined. By default it should match the method name (:layout
corresponds to Layout
).
来源:https://stackoverflow.com/questions/23348610/rails-calling-one-model-from-another-model-why-is-this-not-possible