0

My app has the following models

class Metric < ApplicationRecord
  belongs_to :post

  def analyse!
    client = ThirdPartyService.new
    res = client.get_metrics post.body
    # how to update itself here with the result of res?
  end
end
class Post < ApplicationRecord
  has_many :metrics

  after_save :start_analysis

  private

  def start_analysis
    metric = create_metric
    metric.analysis!
  end
end

The Metric table has a bunch of metrics, like:

adverbs_percentage
sentiment

and the returning result of calling:

client = ThirdPartyService.new
res = client.get_metrics post.body

is a hash containing those exactly props:

{
  :adverbs_percentage => 10
  :sentiment => 'Positive'
}

I would like to know how can I update the Metric from the analyse! method, something like:

update_myself(res)

Thank you.

Amanda Ferrari
  • 1,168
  • 5
  • 17
  • 30

2 Answers2

2

I believe you can do:

class Metric < ApplicationRecord
  belongs_to :post

  def analyse!
    client = ThirdPartyService.new
    res = client.get_metrics post.body
    update res
  end
end
jvillian
  • 19,953
  • 5
  • 31
  • 44
0

According to the Rails documentation, you can update your model in the following way.

m = Metric.first
m.adverbs_percentage= 10
m.sentiment= 'Positive'
m.save

In the above example, adverbs_percentage=, sentiment=, save are instance method of Metric class.
You defined these instance methods by inheriting ApplicationRecord.

Since they are instance method, you can call these methods in your instance method(analyse!).

class Metric < ApplicationRecord
  belongs_to :post

  def analyse!
    client = ThirdPartyService.new
    res = client.get_metrics post.body

    self.sentiment = res.sentiment
    self.adverbs_percentage = res.adverbs_percentage 
    save
  end
end

Note that adverbs_percentage= and sentiment= needs self., because ruby need to distinguish them from local variable assignment.
See here for more detail.

Christian
  • 4,902
  • 4
  • 24
  • 42
s sato
  • 181
  • 8