开发者

rails belongs to conflict?

sorry if a similar question has been posted before, i didn't know what terms to use to search for it.

i have a model 'vehicle_workshop', it stores both vehicles and workshop data, t开发者_运维技巧here are is column called 'type' to distinguish between the two, 'workshop_no' column serves as a name

now i have another model 'workshop distributions', it uses both vehicles and workshops, i am able to create a relationship as follows

belongs_to :vehicle_workshop
belongs_to :vehicle_workshop, :foreign_key => "vehicle_id"

this allows me to save the data, with no issues, the two forign key fields are 'vehicle_workshop_id' for workshops and 'vehicle_id' for vehicles.

now the problems is when i want to access the registration no, i.e the field 'workshop_no' for both vehicles and workshops.

i have 2 attr_accessor's , 'vehicle_no' , 'workshop_no'

the methods are as follows

def vehicle_no
    self.vehicle_workshop ? self.vehicle_workshop.workshop_no : nil
end

def workshop_no
    self.vehicle_workshop ? self.vehicle_workshop.workshop_no : nil
end

both these functions returns the same value, how will i pass the appropriate id values to both these functions? say 'vehicle_id' and 'vehicle_workshop_id' ?

any help would be greatly appreciated.


class WorkshopDistribution
  # You could change your references to these:
  belongs_to :vehicle_workshop
  belongs_to :vehicle, :foreign_key => "vehicle_id", :class_name => 'VehicleWorkshop'

  # and then just change methods:
  def vehicle_no
    vehicle ? vehicle.workshop_no : nil
  end 

  def workshop_no
    vehicle_workshop ? vehicle_workshop.workshop_no : nil
  end
end

but I would suggest you to use STI(Single Table Inheritance) for such situation, if you have a possibility to change DB structure.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜