I have a for loop that is supposed to loop through an object's keys and I've noticed that it seems to exit on the first iteration. My controller initializes my service with the current date and calls parse_leads. parse_leads then calls grouped_leads_by_location and starts looping through the returned object. This loop is the one that seems to exit on first iteration.
# Controller
def generate_invite_texts
params[:signature] == ENV['TEMPORIZE_KEY'] ? valid = true : valid = false
if valid
p "Valid: generate invite texts, #{Time.current.in_time_zone('America/New_York')}"
SakariService.new(Time.current.in_time_zone('America/New_York').to_date).parse_leads
else
p "invalid key: generate invite texts"
end
head :ok
end
# SakariService.rb
class SakariService
include HTTParty
attr_reader :date
base_uri 'https://api.sakari.io'
def initialize(date, no_auth = false)
#options = {
headers: {
'Content-Type' => 'application/json'
}
}
#attempts = 0
#date = date.to_date.end_of_day
#potential_clients = PotentialClient.date_filter(#date.beginning_of_day, #date.end_of_day)
end
# ******************************************************************
# Begin functionality for scheduling the texts to be sent
# ******************************************************************
def parse_leads
grouped_leads_by_location.keys.each do |location_id|
p "LocationID: #{location_id}"
send_text_at = calc_send_time(location_id)
p "Send text at: #{send_text_at}"
schedule_text(send_text_at, location_id) if send_text_at.present?
end
end
# Adds two business days and 2 hours to date
def calc_send_time(location_id)
start_date_range = Date.current + 2.days
end_date_range = start_date_range + 4.days
date_range = ( start_date_range .. end_date_range )
location = Location.find(location_id)
p "start: #{start_date_range}"
p "end: #{end_date_range}"
p "range: #{date_range}"
date_range.each do |possible_date|
p "testing: #{possible_date}"
if !is_weekend?(possible_date) and !Location.is_holiday?(possible_date) and location.is_open_by_date?(possible_date)
time = location.get_open_time(possible_date) + 2.hours
send_text_at = Time.zone.parse("#{possible_date.strftime("%F")} #{time.strftime("%T")}")
return send_text_at
break
end
end
return nil
end
def grouped_leads_by_location
grouped_leads = #potential_clients \
.group_by { |pc| pc.location_id } \
.keep_if { |k, v| !k.nil? }
# outputs something like: { "1" => [#<PotentialClient:0x00000006cb1910> {...}, ...], "2" => [#<PotentialClient:0x00000006cb1910> {...}, ...]}
end
def schedule_text(datetime, location_id)
p "scheduling text: #{location_id} - #{datetime}"
datetime = datetime.to_datetime
SakariTextWorker.perform_at(datetime, #date, location_id)
end
end
In my logs I see the following:
"Valid: generate invite texts, 2020-04-11"
"potential_clients"
D, [2020-04-11T04:56:02.562327 #4] DEBUG -- : [7b48a6db-0d4c-4dd2-9ed5-d436eab62e57] PotentialClient Load (5.7ms) SELECT "potential_clients".* FROM "potential_clients" WHERE (potential_clients.created_at >= '2020-04-11 04:00:00' and potential_clients.created_at <= '2020-04-12 03:59:59.999999')
"LocationID: 40"
D, [2020-04-11T04:56:02.564703 #4] DEBUG -- : [7b48a6db-0d4c-4dd2-9ed5-d436eab62e57] Location Load (0.7ms) SELECT "locations".* FROM "locations" WHERE "locations"."id" = $1 LIMIT $2 [["id", 40], ["LIMIT", 1]]
"start: 2020-04-13"
"end: 2020-04-17"
"range: 2020-04-13..2020-04-17"
"testing: 2020-04-13"
"Send text at: 2020-04-13 11:00:00 -0400"
"scheduling text: 40 - 2020-04-13 11:00:00 -0400"
As you can see the loop runs for location_id 40 and then never continues. After re-running the query, grouped_leads_by_location.keys returns ["40", "3", "42", "75", "1", "5", "2"] so it should have continued. Any idea why this is happening?
Related
I have code to send invites to members of my website and it can be sent via email, real-time notification or One Signal. The code works great in development until I move the invite to an ActiveJob to be processed in the background using Sidekiq and Redis. I am doing this only for when a maintainer of an organization uploads a CSV file of contacts to invite to their organization. (Thus the background job as some clients wish to invite around 10,000+ people which would bog the system if done within the controller.)
If I move the task to an ActiveJob, I get this error in the Sidekiq output:
WARN: NameError: uninitialized constant DeliveryMethods
I thought that this was because I didn't put a require statement in the ActiveJob, so I added this to the top of the ActiveJob:
require 'application_notification'
But, I get the same error message.
I am at a loss. Any help would be greatly appreciated. Here are code snippets. Please let me know if you need anything else.
Versions
Ruby:'3.0.2'
Rails: 7.0.0.alpha
gem 'rails', :github => 'rails/rails', :branch => 'main'
Redis: '~> 4.1.3'
Sidekiq: '6.0.7'
Result Output
# Terminal Output
Started POST "/import_wizard/organization/1" for ::1 at 2021-08-10 16:47:30 -0700
Processing by InvitationsController#invite_imports as JS
Parameters: {"authenticity_token"=>"--REDACTED--", "invitable_type"=>"organization", "invitable_id"=>"1"}
Member Load (1.1ms) SELECT "members".* FROM "members" WHERE "members"."id" = $1 ORDER BY "members"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ app/controllers/concerns/cookies_concern.rb:171:in `load_cookies'
Organization Load (1.3ms) SELECT "organizations".* FROM "organizations" WHERE "organizations"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ app/controllers/invitations_controller.rb:216:in `set_invitable'
ImportResult Load (0.8ms) SELECT "import_results".* FROM "import_results" WHERE "import_results"."invitable_id" = $1 AND "import_results"."status" = $2 LIMIT $3 [["invitable_id", 1], ["status", 1], ["LIMIT", 1]]
↳ app/controllers/invitations_controller.rb:261:in `set_imports_to_invite'
ImportRecord Load (0.7ms) SELECT "import_records".* FROM "import_records" WHERE "import_records"."import_result_id" = $1 AND "import_records"."status" = $2 [["import_result_id", 32], ["status", "ready"]]
↳ app/controllers/invitations_controller.rb:155:in `invite_imports'
[ActiveJob] Enqueued InviteImportedMembersJob (Job ID: 69355585-cfef-4f1f-bf90-eae0f24d5f98) to Sidekiq(imports) with arguments:
#<GlobalID:0x00007fbeba81d0a0 #uri=#<URI::GID gid://prayer-nook/Organization/1>>,
[#<GlobalID:0x00007fbeba81c6a0 #uri=#<URI::GID gid://prayer-nook/ImportRecord/309>>,
#<GlobalID:0x00007fbeba817d08 #uri=#<URI::GID gid://prayer-nook/ImportRecord/310>>,
#<GlobalID:0x00007fbeba817470 #uri=#<URI::GID gid://prayer-nook/ImportRecord/311>>,
#<GlobalID:0x00007fbeba816d68 #uri=#<URI::GID gid://prayer-nook/ImportRecord/312>>,
#<GlobalID:0x00007fbeba816250 #uri=#<URI::GID gid://prayer-nook/ImportRecord/313>>,
#<GlobalID:0x00007fbeba8157b0 #uri=#<URI::GID gid://prayer-nook/ImportRecord/318>>,
#<GlobalID:0x00007fbeba814a40 #uri=#<URI::GID gid://prayer-nook/ImportRecord/319>>],
#<GlobalID:0x00007fbeb9a5f198 #uri=#<URI::GID gid://prayer-nook/Member/1>>
Rendering invitations/invite_imports.js.erb
Rendered invitations/invite_imports.js.erb (Duration: 0.1ms | Allocations: 10)
Completed 200 OK in 317ms (Views: 3.4ms | ActiveRecord: 95.8ms | Allocations: 57969)
Controller Action
The commented out line for invite_imports_task is a method I made within the controller with the exact same code that runs in the ActiveJob, but works. So, I know that the code works, its just moving to an ActiveJob that is now causing the issue.
# InvitationsController#invite_imports
# app/controllers/invitations_controller.rb
def invite_imports
set_invitable
set_imports_to_invite
#import_step = 4
imports_to_invite_array = []
#imports_to_invite.each do |record|
imports_to_invite_array << record
end
InviteImportedMembersJob.perform_later(#invitable, imports_to_invite_array, #authenticated_member)
# invite_imports_task(#invitable, imports_to_invite_array, #authenticated_member)
respond_to do |format|
format.js
end
end
Active Job
# app/jobs/invite_imported_members_job.rb
class InviteImportedMembersJob < ApplicationJob
require 'application_notification'
queue_as :imports
def perform(invitable, imports_to_invite, sender)
set_import_result(invitable)
imported_emails = imports_to_invite.map {|member| member[:email]}
member_list = Member.where(email: imported_emails)
member_email_list = member_list.pluck(:email)
non_member_email_list = imported_emails - member_email_list
sent_invites = []
error_in_sending_invites = []
member_list.each do |member|
invitation = Invitation.new(invitable: invitable, sender: sender, recipient:member)
if invitation.save
invitable.invited_members << member
sent_invites << member.email
else
error_in_sending_invites << member.email
end
end
non_member_email_list.each do |member|
InvitationMailer.with(recipient_email: member, sender: sender).app_invitation.deliver_later
waitlist = InvitationWaitlist.create(email: member, invitable: invitable, sender: sender)
# in this case the member variable is only an email address
if waitlist.save
sent_invites << member
else
error_in_sending_invites << member
end
end
update_import_records(invitable, sent_invites, error_in_sending_invites)
update_import_result
create_cue_notification(invitable)
end
private
def set_import_result(invitable)
#import_result = ImportResult.find_by(invitable:invitable, status: 'waiting')
end
def update_import_records(invitable, sent_invites, error_in_sending_invites)
if sent_invites.count > 0
ImportRecord.where(import_result_id:#import_result.id, email: sent_invites).update_all(status:'sent')
end
if error_in_sending_invites.count > 0
ImportRecord.where(import_result_id:#import_result.id, email: error_in_sending_invites).update_all(status:'error_in_sending')
end
end
def update_import_result
#import_result.completed!
end
def create_cue_notification(invitable)
hide_old_cues(invitable)
CueService.new(#import_result, set_cue_recipients(invitable), false).call!
end
def hide_old_cues(invitable)
Cue.where(cueable: #import_result).update(status:'hidden')
end
def set_cue_recipients(invitable)
if invitable.is_a?(Organization)
return invitable.maintainers
elsif invitable.is_a?(Group)
return invitable.owner
else
return nil
end
end
end
Application Notification
# app/notifications/application_notification.rb
class ApplicationNotification < Noticed::Base
deliver_by :database, format: :format_for_database
deliver_by :action_cable, channel: 'NotificationsChannel', format: :format_for_action_cable
deliver_by :one_signal, class: "DeliveryMethods::OneSignal", format: :format_for_one_signal
def format_for_database
{
type: self.class.name,
params: params
}
end
end
DeliveryMethod::OneSignal
# app/notifications/delivery_methods/one_signal.rb
class DeliveryMethods::OneSignal < Noticed::DeliveryMethods::Base
def deliver
return unless app_id.present? && one_signal_url.present? && player_id.present?
params = {"app_id" => app_id,
"contents" => {"en" => message},
"headings" => {"en" => "Prayer Nook"},
"include_player_ids" => [player_id],
"data" => data
}
uri = URI.parse(one_signal_url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.path,'Content-Type' => 'application/json;charset=utf-8')
request.body = params.as_json.to_json
response = http.request(request)
puts "OneSignal response: #{response.body}"
end
private
def app_id
ENV['ONE_SIGNAL_APP_ID']
end
def one_signal_url
ENV['ONE_SIGNAL_API_URL']
end
def player_id
recipient.site_profile.one_signal_id
end
def message
if (method = options[:format])
notification.send(method)[:message]
else
"Message from Prayer Nook"
end
end
def data
if (method = options[:format])
notification.send(method)[:data]
else
{ }
end
end
end
From the Invitation Model
## app/models/invitation.rb
def send_notifications
if self.invitable_type == 'Group'
GroupInvitationNotification.with(invitation: self, group: self.invitable, sender: self.sender).deliver_later(self.recipient)
elsif self.invitable_type == 'Organization'
OrgInvitationNotification.with(invitation: self, organization: self.invitable, sender: self.sender).deliver_later(self.recipient)
end
end
OrgInvitationNotification
# app/notifications/org_invitation_notification.rb
class OrgInvitationNotification < ApplicationNotification
# this class inherits other delivery methods from ApplicationNotification: database, action_cable, and one_signal
deliver_by :email, mailer: "InvitationMailer", method: :org_invitation, if: :immediate_email_notifications?
# required params
param :invitation
param :organization
param :sender
# helper methods to make rendering easier.
def format_for_action_cable
html = ApplicationController.render(
partial: 'notifications/toast',
locals: { header: "You've been invited",
message: message,
link_path: invitation_path(params[:invitation])
}
)
params.merge(html: html)
end
def format_for_one_signal
{
message: message,
data: { page: 'invitation', id: params[:invitation].id }
}
end
def immediate_email_notifications?
recipient.site_profile.invitations_email_notifications == 'immediately'
end
def message
t(".message", sender: params[:sender].full_name, org_name: params[:organization].name)
end
def url
invitation_url(params[:invitation])
end
end
Update
New code block per #LamPhan's comments:
# From config/application.rb
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.0
config.active_job.queue_adapter = :sidekiq
config.active_record.encryption.support_unencrypted_data = true
config.active_record.legacy_connection_handling = false
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
config.generators do |g|
g.test_framework :rspec,
fixtures: false,
view_specs: false,
helper_specs: false,
routing_specs: false
end
config.autoloader = :classic
end
According to comments, you're using :classic loader and your project're running on Rails 7.0.
Base on this comment (of the creator of sidekiq): Sidekiq does not work with the classic autoloader in Rails 6 at all.
so you should use :zeitwerk loader.
The following unit test succeeds in the first assertion, but fails in the second
test "login_name, kee and virtual_qr changed" do
#user = users(:funky_mobile)
assert_changes 'users(:funky_mobile).mobile' do
#user.update(address: 'muuvt', mobile: '728363', mobile_nation_id: 1)
# patch update_user_path(#user_mobile), params: { user: { address: 'muuvt', mobile: '728364', mobile_nation_id: 1 } }
end
assert_changes 'users(:funky_mobile).login_name' do
#user.update(address: 'muuvt', mobile: '728365', mobile_nation_id: 1)
end
end
"users(:funky_mobile).login_name" didn't change.
Note: while patch - attempted as per the following - does process correctly, it appears not applicable to a unit test.
The unit test with update only registers the submitted params but does not kick in the before_action, as per test.log
User Update (0.5ms)[0m [1m[33mUPDATE "users" SET "mobile" = $1 WHERE "users"."id" = $2[0m [["mobile", 728365], ["id", 165956397]]
Conversely, with an integration test
sign_in users(:funky_mobile)
assert_changes 'users(:funky_mobile).login_name' do
patch user_url(#user_mobile), params: { user: { address: 'muuvt', mobile: '728364', mobile_nation_id: 1 } }
end
"users(:funky_mobile).login_name" didn't change.
Expected nil to not be equal to nil.
the changed data enacted via before_action :set_user_login_name, only: %i[ update ] of the users_controller
def set_user_login_name
if params[:user][:email].present?
params[:user][:login_name] = params[:user][:email].gsub(/\s+/, "")
elsif params[:user][:mobile_nation_id].present? && params[:user][:mobile].present?
#nation = Nation.where(id: params[:user][:mobile_nation_id]).first
params[:user][:login_name] = #nation.phone_cc.to_s + params[:user][:mobile].to_s
params[:user][:twilio_number] = '+' + #nation.phone_cc.to_s + params[:user][:mobile].to_s
else
params[:user][:login_name]
end
params[:user][:kee] = SecureRandom.alphanumeric(32)
params[:user][:virtual_qr_code] = params[:user][:login_name] + params[:user][:kee]
end
is processed as demonstrated by the test.log
User Update (0.7ms)[0m [1m[33mUPDATE "users" SET "login_name" = $1, "kee" = $2, "virtual_qr_code" = $3 WHERE "users"."id" = $4[0m [["login_name", "39728364"], ["kee", "Rce8sQoH0VPvqUPeuegZL4gYVmJuamqi"], ["virtual_qr_code", "39728364Rce8sQoH0VPvqUPeuegZL4gYVmJuamqi"], ["id", 165956397]]
TRANSACTION (0.1ms)[0m [1m[35mRELEASE SAVEPOINT active_record_1[0m
Redirected to http://www.example.com/users/165956397
Oddly, if the integration test is altered reomving assert_changes to simply
patch user_url(#user_mobile), params: { user: { address: 'muuvt', mobile: '728364', mobile_nation_id: 1 } }
puts #user_mobile.mobile
assert_equal(39728364, #user_mobile.mobile)
returns
3331112200
F [...]
Expected: 39728364
Actual: 3331112200
yet the log shows the same User update reference as above.
How can I properly assert that these changes are being carried forth?
This is going to fail...
assert_changes 'users(:funky_mobile).login_name' do
because...
users(:funky_mobile).login_name
returns the original value every time. It is calling the fixture and acts like a constant.
What you should do is...
login_name = users(:funky_mobile).login_name
assert_changes login_name do
My Class:
class TtsGoogle
def initialize
#google_client = Google::Cloud::TextToSpeech.text_to_speech
end
def write_file(topic)
text = topic.content
spaces = text.enum_for(:scan, /(?=\s)/).map { Regexp.last_match.offset(0).first }
start = finish = limit = 0
result = ''
while true do
#Google TTS limit 5000
limit += 4800
if limit < text.length
finish = spaces.select {|n| n > limit }.first
result += get_audio_content(text[start..finish])
start = finish
else
result += get_audio_content(text[start..text.length])
break
end
end
File.open "#{topic.name.gsub('/', ' ')}.wav", "wb" do |file|
file.write result
end
end
def delete_file(name)
File.delete("#{name.gsub('/', ' ')}.wav")
end
private
def get_audio_content(text)
synthesis_input = { text: text }
response = #google_client.synthesize_speech(
input: synthesis_input,
voice: voice_config,
audio_config: audio_config
)
response.audio_content
end
def voice_config
#voice_config ||= {
language_code: "en-US",
ssml_gender: "NEUTRAL",
name: "en-US-Wavenet-B"
}
end
def audio_config
#audio_config = { audio_encoding: "LINEAR16", speaking_rate: 0.90 }
end
end
And when I try to create audio from big text, I have this trouble:
Google::Cloud::ResourceExhaustedError 8:Received message larger than max (5250205 vs. 4194304)
With small text it work, when audio on the out less then 4MB. How I can increase or disable this 4MB limit? I found some solution for PHP, where used next way:
-$client = new TextToSpeechClient();
+$client = new TextToSpeechClient([
'transportConfig' => [
'grpc' => [
'stubOpts' => [
'grpc.max_receive_message_length' => -1,
'grpc.max_send_message_length' => -1
]
]
]
]);
But I don't know, how to fix this issue with Rails. Help please.
I am trying to get series from the movie database in multiple languages.
My goal is to update the object returned by the API to have the following keys :
name_en, name_fr, overview_en, overview_fr
I have this piece of code :
require 'httparty'
class GetSeriesJob < ApplicationJob
queue_as :default
API_URL = 'https://api.themoviedb.org/3/'
LANGS = {'fr' => '&language=fr-FR', 'en' => '&language=en-EN'}
def perform
get_series
end
private
def get_series
seriesArray = []
LANGS.each do |lang|
series = HTTParty.get(API_URL + 'tv/popular?api_key=' + ENV['API_KEY'] + lang[1])
tmp = JSON.parse(series.body)['results']
tmp.each do |t|
if seriesArray.detect{ |s| s['id'] == t['id'] }
t['name_' + lang[0]] = t['name']
t['overview_' + lang[0]] = t['overview']
else
t['name_' + lang[0]] = t.delete t['name']
t['overview_' + lang[0]] = t.delete t['overview']
end
end
seriesArray = tmp
end
puts seriesArray
return seriesArray
end
end
Which return (for one series) :
[["original_name", "The Expanse"], ["name_en", "The Expanse"], ["popularity", "66.679301"], ["origin_country", "[\"US\"]"], ["vote_count", 564], ["first_air_date", "2015-12-14"], ["backdrop_path", "/beIjmWr3OBOtcWK4tKMObOIDJ1C.jpg"], ["original_language", "en"], ["vote_average", 7.5], ["overview_en", "A thriller set two hundred years in the future following the case of a missing young woman who brings a hardened detective and a rogue ship's captain together in a race across the solar system to expose the greatest conspiracy in human history."], ["poster_path", "/prJFWxJ0x8tBPTliMjj51wgYnSK.jpg"], ["episode_run_time", "[43]"], ["number_of_seasons", 3], ["external_id", 63639], ["created_at", "2018-06-24 13:40:16.143952"], ["updated_at", "2018-06-24 13:40:16.143952"]]
And I would expect the following result :
[["original_name", "The Expanse"], ["name_en", "The Expanse"], ["name_fr", "The Expanse"]["popularity", "66.679301"], ["origin_country", "[\"US\"]"], ["vote_count", 564], ["first_air_date", "2015-12-14"], ["backdrop_path", "/beIjmWr3OBOtcWK4tKMObOIDJ1C.jpg"], ["original_language", "en"], ["vote_average", 7.5], ["overview_en", "A thriller set two hundred years in the future following the case of a missing young woman who brings a hardened detective and a rogue ship's captain together in a race across the solar system to expose the greatest conspiracy in human history."], ["overview_fr", "overview in French."] ["poster_path", "/prJFWxJ0x8tBPTliMjj51wgYnSK.jpg"], ["episode_run_time", "[43]"], ["number_of_seasons", 3], ["external_id", 63639], ["created_at", "2018-06-24 13:40:16.143952"], ["updated_at", "2018-06-24 13:40:16.143952"]]
I am using ruby on rails 5.2
So, I found myself a way to solve my issue, here are the relevant modifications
def get_series
seriesArray = []
LANGS.each do |lang|
series = HTTParty.get(API_URL + 'tv/popular?api_key=' + ENV['API_KEY'] + lang[1])
tmp = JSON.parse(series.body)['results']
tmp.each do |t|
if serie = seriesArray.detect{ |s| s['id'] == t['id'] }
serie['name_' + lang[0]] = t['name']
serie['overview_' + lang[0]] = t['overview']
serie['genre_' + lang[0]] = t['genre_ids']
serie.delete('name')
serie.delete('overview')
serie.delete('genre_ids')
else
t['name_' + lang[0]] = t['name']
t['overview_' + lang[0]] = t['overview']
t['genre_' + lang[0]] = t['genre_ids']
end
end
if seriesArray.count == 0
seriesArray = tmp
end
end
return seriesArray
end
I want to let a user edit the field report.plan only if report.published = false. If report.published = true and they try to save a change, I want to throw an error.
I've written the following code to do this:
class Report < ActiveRecord::Base
validate :cannot_update_plan_after_published, on: :publish_plan!
def publish_plan!(plan)
self.plan = plan
self.published = true
self.save
end
private
def cannot_update_plan_after_published
if self.published?
errors.add(:plan, "You cannot change the plan once it has been published.")
end
end
end
However, this is not working. When I call publish_plan! on an already published report, it makes the save. For example:
> f = Report.last
=> #<Report id: 12, plan: "a", published: false>
> f.publish_plan!("b")
(0.1ms) begin transaction
(0.4ms) UPDATE "reports" SET "plan" = 'b', "updated_at" = '2014-09-18 18:43:47.459983' WHERE "reports"."id" = 12
(9.2ms) commit transaction
=> true
> f = Report.last
Report Load (0.2ms) SELECT "reports".* FROM "reports" ORDER BY "reports"."id" DESC LIMIT 1
=> #<Report id: 12, plan: "b", published: true>
> f.publish_plan!("c")
(0.1ms) begin transaction
(0.4ms) UPDATE "reports" SET "plan" = 'c', "updated_at" = '2014-09-18 18:43:53.996191' WHERE "reports"."id" = 12
(8.7ms) commit transaction
=> true
> Report.last
Report Load (0.2ms) SELECT "reports".* FROM "reports" ORDER BY "reports"."id" DESC LIMIT 1
=> #<Report id: 12, plan: "c", published: true>
How do I get this field to become uneditable once report.published = true?
Try removing the on: :public_plan!. That way, the validation should be run every time the model is saved.
validate :cannot_update_plan_after_published
See here for more details: Adding a validation error with a before_save callback or custom validator?
Also, for the validation method itself, change it to the following:
def cannot_update_plan_after_published
if self.published? && self.published_changed? == false
errors.add(:plan, "You cannot change the plan once it has been published.")
end
end
This allows you to set it the first time publishing the plan.