简体   繁体   中英

How to share data between two models in Ruby on Rails

Hi I am implementing a web app on RoR. My first model has got three fields as input (weight, height and gender) while my second model has got 2 fields (weight and height). I have implemented the first model and am thinking to create a separate model for the one with two fields. The task is that when I put data into second model (which i am thinking to implement), my code should extract all the data from the first model ie the one with three fields, and then I should perform calculations on it.

My question is:

Will the same db be shared between these two models? and how should i extract the data from the first model when I enter and submit the data into second model form?

From the details of your question it's not entirely certain, but perhaps Single Table Inheritance could help you here.

Basically you can have these models:

class BaseModel < ActiveRecord::Base; end
class ThreeFieldModel < BaseModel; end
class TwoFieldModel < BaseModel; end

Your migration would contain all fields including a magical type column:

create_table :base_model do |t|
  t.string :type,   null: false
  t.string :weight
  t.string :height
  t.string :gender
  t.timestamps
end

If you decide to use STI, I recommend to read one or two tutorials regarding this topic. Properly using STI with Rails can be difficult at times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM