Question

In my view I have

<%= version.object_changes %>

Here is an example of it's output

--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess\nmanufacturer_id:\n- \n- 2\nminiature_id:\n- \n- 37\ncreated_at:\n- \n- 2014-05-13 15:50:08.685560000 Z\nupdated_at:\n- \n- 2014-05-13 15:50:08.685560000 Z\nid:\n- \n- 59\n

I want to isolate the manufacturer_id and use it to display the manufacturer name.

<%= Manufacturer.find(xxxxx).name %>

I could isolate the manufacturer_id if it was a hash but it's just a text string.

I guess I want a way of saying find the line "manufacturer_id: - - x" and take "x". Is that possible?

Was it helpful?

Solution

You didn't mention it in your question, but I think you are using paper_trail gem in your code.

version.object_changes stores the data in text form in database, so, you can't extract id from that like this. But you can use version.changeset to get the changes in hash.

Read more about it on their documentation here.

The best way to diff adjacent versions is to get PaperTrail to do it for you. If you add an object_changes text column to your versions table, either at installation time with the rails generate paper_trail:install --with-changes option or manually, PaperTrail will store the changes diff (excluding any attributes PaperTrail is ignoring) in each update version. You can use the version.changeset method to retrieve it.

EDIT: Based on the comment by OP below and update in answer, I will suggest extraction with regexp like:

if exp = version.object_changes.match(/manufacturer_id:\n- \n- (\d+)/)
  exp[1]
end
=> "9"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top