How to execute a raw update sql with dynamic binding in rails

It doesn’t look like the Rails API exposes methods to do this generically. You could try accessing the underlying connection and using it’s methods, e.g. for MySQL: st = ActiveRecord::Base.connection.raw_connection.prepare(“update table set f1=? where f2=? and f3=?”) st.execute(f1, f2, f3) st.close I’m not sure if there are other ramifications to doing this (connections left open, … Read more

Rails – Validate Presence Of Association?

You can use validates_presence_of http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates_presence_of class A < ActiveRecord::Base has_many :bs validates_presence_of :bs end or just validates http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates class A < ActiveRecord::Base has_many :bs validates :bs, :presence => true end But there is a bug with it if you will use accepts_nested_attributes_for with :allow_destroy => true: Nested models and parent validation. In this topic you … Read more

ActiveRecord, has_many :through, and Polymorphic Associations

There is a known issue with Rails 3.1.1 that breaks this functionality. If you are having this problem first try upgrading, it’s been fixed in 3.1.2 You’re so close. The problem is you’re misusing the :source option. :source should points to the polymorphic belongs_to relationship. Then all you need to do is specify :source_type for … Read more

Rails create or update magic?

Rails 6 Rails 6 added an upsert and upsert_all methods that deliver this functionality. Model.upsert(column_name: value) [upsert] It does not instantiate any models nor does it trigger Active Record callbacks or validations. Rails 5, 4, and 3 Not if you are looking for an “upsert” (where the database executes an update or an insert statement … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)