Quin
Quin

Reputation: 523

Copying attribute between different models' object but with the same attributes name

** The original question here does not correctly explain what my problem is, Sorry to readers. Could you please refer to the "updated" part? Thanks **

Say I have two models - Questions and SolvedQuestions. What I want to do is to copy the solved Questions to SolvedQuestions. The model would look like this: Questions(id: integer, content: string, user_id: integer) and SolvedQuestions(id: integer, question_id: integer, content: string, user_id: integer, solver_id: integer, solved_at: datetime )

So the question being is there any way to copy the attributes from Questions to SolvedQuestions which have the same attribute name, except explicitly copy the value one by one? The reason being that: 1. That could be more robust in the future when new fields being added to Questions and SolvedQuestions.; 2. Time-saving.

Any thoughts? Thank you :)

Updated: I do agree that a status attribute would do! I think I have picked a very bad example so please accept my apologies. The question I am trying to solve is that users can edit the Questions so I need to keep an instance of all historic questions.

In this case, I should use the example: Questions and QuestionsHistories. That's why I want to copy an image of Questions to QuestionHistories... Thank you!

Upvotes: 1

Views: 348

Answers (2)

Ahmad Hussain
Ahmad Hussain

Reputation: 2491

I think so the best way is to use only one model Question and add a boolean field like solved? and also move solver_id and solved_at in Questions model.

You can filter out with the help of scope

scope :solved, where(:solved => true)
scope :not_solved, where(:solved => false)

Upvotes: 0

Billy Chan
Billy Chan

Reputation: 24815

A better structure

class Question < ActiveRecord::Base      
end

class SolvedQuestion < Question
  # when solved, set solved as true and
  # set question_id in solver.
  has_many :solvers
end

class Solver < ActiveRecord::Base
  belongs_to :solved_question
end

#Migration
create_table questions do |t|
  t.solved :boolean, default: false
  # others
end

Just plain basic ActiveRecord settings. No fancy stuff needed.

Upvotes: 0

Related Questions