Tuesday, March 1, 2011

saving to join model has_many :through

Sequences are acting as a join table between procedures and steps:

  create_table "procedures", :force => true do |t|
    t.integer  "procedure_id"
    t.integer  "revision"
    t.string   "description"
  end

  create_table "sequences", :force => true do |t|
    t.integer  "procedure_id"
    t.integer  "step_id"
    t.integer  "step_number"
  end

  create_table "steps", :force => true do |t|
    t.string   "descriptor"
    t.string   "step_category"
    t.string   "step_type"
    t.text     "instructions"
  end

What I am trying to do is to create a procedure, then create a step from the procedure, and have it save the step_number in the sequence associating the step and the procedure at the same time.

  1. Is there any good guide on how to do has_many :through? All I ever find is just how to make the model, I have no idea how to work with it.
  2. When saving my Step, do I need to explicitly create a Sequence? I was hoping Rails would automagically create it.

If anyone has some pointers on how to do this I would be glad to hear them, I'm having a lot of trouble setting this up.

From stackoverflow
  • Rails does not automatically create join records for you expect when using "has and belongs to many". If you are using "has many :through" you will have to explicitly create the join record. However, this doesn't stop you from making a helper method to do some of the dirty work for you.

    Karl : One more question then: Would it be possible to access the step_number by doing something like @step.step_number? Or do I have to go and find the associated Sequence to access this?
    Peter Wagenet : Are you planning to have a step only associated with a single procedure? If so, then you don't really need to have the sequences table and you can save yourself some trouble. If, on the other hand, a step can belong to multiple difference procedures (via sequences) then you can't know what step_number you want, unless you know what procedure it is. You could in that case have something like @step.step_number(procedure).
    Karl : It is necessary to be able to have a step in multiple procedures. From what I can tell, I pretty much have to pull out the revision from the database explicitly in order to get the step_number. A bit of a hassle, but I guess it's the only way.

0 comments:

Post a Comment