0

I am working on the scenario which is different and I have model structures like

This is my main model which has STI and working fine.

class Post < ActiveRecord::Base
  # table is "posts" as per default behaviour
  # have column "type"
end

This is my another model is FakePost (looks weird but required :( ). This is totally clone structure of Post model. These objects will be become Post object as per requirement.

My problem is to keep type column in FakePost but should not use STI.

What I tried is below solution as per Rails -- use type column without STI?

class FakePost < Post
  self.table_name = 'fake_posts'
  private

  def self.inheritance_column
    nil
  end
end

Above solution doesn't work. Because it is running the below querie

irb(main):001:0> FakePost.first

  FakePost Load (1.0ms)  SELECT  "fake_posts".* FROM "fake_posts"  WHERE "fake_posts"."type" IN ('FakePost')  ORDER BY "fake_posts"."id" ASC LIMIT 1
=> nil

What I want is that type based queries shouldn't run.

Is there any solution what I can do.

Because I can rename the column but when I convert FakePost object to Post object then I can't directly use dup.

Please let me know if I am not much clear and need more information.

Sourabh
  • 21
  • 2
  • You can try not to inherit your `FakePost` from `Post`. Inheritance should be used for specialization, not for sharing functionality. You can share functionality with model concerns or something like that. This should disable STI in your case. :) – Sergio Tulentsev Jul 27 '17 at 09:17
  • Nice suggestion but there is not option(window) to make such changes, I tried to disable STI but seems not working. – Sourabh Jul 27 '17 at 09:26
  • Also, it's not well documented, but you can use `#initialize_copy(copy)` if you need to do stuff while calling [`dup`](https://ruby-doc.org/core-2.4.1/Object.html#method-i-dup). It gets called on the original and passed in the new copy – Simple Lime Jul 27 '17 at 09:26
  • @SimpleLime, I didn't get you, can you explain what exactly you targeting? – Sourabh Jul 27 '17 at 09:35
  • I'm not 100% sure I followed this question but you mentioned in it "I can rename the column but when I convert FakePost object to Post object then I can't directly use dup." So if the only reason you weren't doing that was so you could call `dup` on a FakePost to make it into a normal post, you can set up an `initialize_copy` method that kind of "post-processes" the new copy during the copy process. So you can still just call `dup` and have extra stuff take place – Simple Lime Jul 27 '17 at 09:37
  • @SimpleLime, thanks I got your point, let me try. – Sourabh Jul 27 '17 at 09:44
  • @SimpleLime - Not working, initialize_copy doesn't called by `dup` and dup don't expect params. – Sourabh Jul 27 '17 at 12:22

0 Answers0