Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Have you looked into <a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html" rel="nofollow noreferrer">Single Table Inheritance</a>? I think it's the all around best solution for you here.</p> <p>Essentially you define an hours table and model, that looks exactly like either staff hours or business hours and includes a string column named type. Then you create subclasses of Hours to define methods and validations specific to Business and Staff hours respectively. You also might want to redefine your association to something more generic. In the example, I've called it keeper, as on one who keeps those hours.</p> <p>In a nutshell rails is handling all the polymorphic behaviour for you.</p> <p>Models:</p> <pre><code>class Hour &lt; ActiveRecord::Base # common associations/methods etc go here end class BusinessHour &lt; Hour belongs_to :keeper, :class_name =&gt; "Business" #business hour specific logic end class StaffHour &lt; Hour belongs_to :keeper, :class_name =&gt; "Staff" #staff hour specific logic end class Business &lt; ActiveRecord::Base has_many :business_hours, :foreign_key =&gt; :keeper_id ... end class Staff &lt; ActiveRecord::Base has_many :staff_hours, :foreign_key =&gt; :keeper_id ... end </code></pre> <p>Route:</p> <pre><code>map.resources :business_hours, :controller =&gt; "hours", :class =&gt; "BusinessHour" map.resources :staff_hours, :controller =&gt; "hours", :class =&gt; "StaffHour" </code></pre> <p>Controller:</p> <pre><code>class HoursController &lt; ApplicationController before_filter :select_class def select_class @class = Kernel.const_get(params[:class]) end def new @hour = @class.new ... end def show @hour = @class.find(params[:id]) ... end ... end </code></pre> <p>Views will look almost exactly what you have now, but you're going to want some helpers to keep the output straight.</p> <pre><code>module HourHelper def keeper_type @class == "BusinessHours" ? "Business" : "Staff" end end -form_for(obj) do |f| =f.error_messages %p =select keeper_type, :mon_start_time, hours to =select keeper_type, :mon_stop_time, hours =link_to 'Back', obj_path </code></pre> <p>You might also want to consider creating a custom form builder to simplify the form creation.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload