Rails: Prevent Delete and Destroy of active record - ruby

I need to maintain data integrity and prevent any deletions from the database.
I saw ways to prevent the destroy method, using this technic:
Rails: How to prevent the deletion of records?
However, how can I prevent both the delete and destroy methods?

To prevent records from being deleted from the database but still provide a good user experience where they can delete (hide) records I like to integrate a soft delete gem like "discard". What this does it adds a new column to your models with discarded_at and then scopes all the records where discarded_at is nil
Step 1) Add the gem
# Gemfile
gem 'discard', '~> 1.2'
Step 2)
bundle_install
Step 3)
Add the Discard include to your models
class Post < ActiveRecord::Base
include Discard::Model
default_scope -> { kept }
...
end
Step 4) Create Migration
rails generate migration add_discarded_at_to_models discarded_at:datetime:index
Here are some basic useage
Model.all # Only kept models
Model.with_discarded # All models
Model.with_discarded.discarded # Only discarded models
I hope that this helps

Related

Is there a way to keep history of states with aasm gem?

I am wondering if this gem provides a way to keep history of states. I probably can do this by adding a callback to each event but I am wondering what other people think about this approach.
I looked at this recently and the two solutions I found were the assm_history gem and paper_trail. Given that I already had paper_trail installed, I ended up going with that.
edit: Per #BKSpurgeon's question below, we ended up adding an after_save callback on the model, and then created a new row in a new table on every state transition. Prior to that, I added a transition from :any => :any and did it there.
after_save -> { record_item_transition }, if: :state_changed?

Rails 4: Append to a "has_many" relation without saving to DB

In Rails 3 one can do things like some_post.comments.append(some_comment) where some posts is an instance of a model that "has_many" comments.
The problem I'm facing in Rails 4 is that the append method now saves to DB (like push and << ) and I need to just "append" without saving the appended object to the DB.
How do we achieve that in Rails 4? I can't use some_post.comments.build(some_comment.attributes) because I need to preserve the other relations already present in the some_comment instance.
It's oddly difficult to do this elegantly in Rails. This is the cleanest way I've found:
post.association(:comments).add_to_target(comment)
You could do:
class Post < ActiveRecord::Base
has_many: comments, autosave: false
...
end
Then << will just append and not save.
You can do it without using reflection on the association:
post.comments.build(
attr_1: value_1,
attr_1: value_2,
# Other comment attributes
)

Active Record class

I am working on a migration project. Wanna migrate a rails 2.x app to 3.x. I have a problem with active record.
In Rails 2.x:
arr=StorageUnit.find(:all, :conditions =>"type='Drawer'")
The above code will get me all records with type Drawer.
arr.class
=> Array
In Rails 3.x:
Here the above function is deprecated. So i had to use
arr=StorageUnit.where("type='Drawer'")
The above code will get me all records with type Drawer.
arr.class
ActiveRecord::Relation
I guess this is because of the change in Active Record.
My problem is i have some code based on this class.
For ex:
if arr.class== Array
do something
else
do something
end
So as off now i have changed it to
if arr.class== ActiveRecord::Relation
do something
else
do something
end
Just curious to know whether there is any better solution or any alternative way to solve it. I have a lot of place where they have used such stuff.
EDIT:
arr=StorageUnit.where("type='Drawer'").all
will provide the class as Array. My objective is to know when the code without suffix can provide you the required records than what is the use of all in the end.? Is it just to change class? Can anyone ecxplain?
StorageUnit.where simply returns the ActiveRecord relation. Tacking on .all will execute the sql and create instances of StorageUnit.
arr = StorageUnit.where(:type => 'Drawer').all
There are many interesting side effects of it being returned as a relation. Amongst other things, you can combine scopes before executing:
StorageUnit.where(:type => 'Drawer').where(:color => 'black')
you can view the resultant sql for debugging:
StorageUnit.where(:type => 'Drawer').to_sql
Imagine this:
class StorageUnit < ActiveRecord::Base
scope :with_drawer, where(:type => 'Drawer')
scope :with_color, lambda { |c| where(:color => c) }
end
Now:
StorageUnit.with_drawer.with_color('black').first_or_create # return the first storage unit with a black drawer
StorageUnit.with_drawer.with_color('black').all # return all storage units with black drawers
The relation allows for underlying query to be built up even saved for later use. all and other modifiers like it have special meaning to the relation and trigger the database execution and building of model instances.

Mongoid has_many relationship causes Rack cookie error in Sinatra

Writing an application using Mongoid 3.1 and Sinatra in Ruby 1.9.3. I have a model called Order that has_many Items. Whenever I try to append an Item to an Order.items, I run into problems. I have the following route, summed up slightly:
order = session[:user].get_order(Time.now)
order.items << Item.new
order.save
"Hi, mom!" # Garbage page so that I know nothing else is called.
Doing that once is okay; doing it twice causes the following error:
Warning! Rack::Session::Cookie data size exceeds 4K.
Warning! Rack::Session::Cookie failed to save session. Content dropped.
I've been banging my head against the wall trying to get it to stop doing this. Why is the session loading all my items? Am I not using the has_many relationship correctly?
Your User model probably has_many :orders. Ruby is probably calling Marshal.dump to dump your user object into the cookie. You can imagine this might get huge. You should do the following:
Only store the user_id in the session.
Store your session server-side instead of in the cookie.
You'll need to use different middleware to store your session server-side. See this page for an example of storing your session in memcache. Since you're already using mongo, you could use Rack::Session::Mongo.
Even though you're not using Rails, the Rails guide on session security is useful reading. [link]

Ignore 'read-only' column in creates and updates in Ruby ActiveRecord

I'm looking for a solution to the following problem: I have an ActiveRecord entity that is backed by an updatable database view (in DB2 via the activerecord-jdbc-adapter gem). This view contains one column that is calculated from other columns and is 'read-only': you cannot set that column in any valid way. When a new record is created for this entity, that field should not be set. However, by default, ActiveRecord does set it with the 'default' (NULL), which is rejected by the database.
attr_readonly isn't a solution, because that only excludes a column from updates and not from creates.
attr_ignore, such as implemented by the 'lincoln' gem, is not a solution either, because then the field is ignored entirely. However, the column still needs to be read and be accessible. It's actually even used as part of a relation.
There are ways to prevent you from setting a certain attribute of an ActiveRecord entity, but that doesn't usually prevent that attribute from being included in create or update statements
Does anyone know if there is a way in ActiveRecord to specify a column as 'never set this field'?
Update, in response to Arsen7:
I've attempted to use the after_initialize hook to remove the attribute from a newly created entity, so it isn't included in the SQL that is built. The trouble with this is that the attribute is completely removed and not available anymore at all, pretty much identical to the 'igonre_attr' situation described above. Due to caching, that's not trivial to get around and would require additional logic to force a reload of entities of these specific tables. That can probably be achieved by overriding create to add a 'reload', in addition to using the after_initialize.
(As pointed out by Arsen7, I forgot to mention I'm at ActiveRecord 3.0.9)
My solution
Since my entities already inherit from a subclass of ActiveRecord::Base, I've opted to add before_create and after_create hooks. In the before_create hook, I remove the 'calculated' columns from the #attributes of the instance. In the after_create hook, I add them again and read the values of the 'calculated' columns from the database to set them to the values they received.
Adding such hooks is almost identical to overriding create, so I consider Arsen7's answer to be correct.
I'm afraid ActiveRecord is not prepared for the use case you need. (By the way: which version of AR are you using?)
But I believe you may apply two possible workarounds.
The first, is to overwrite the 'create' method of your model, executing some other SQL, prepared manually in the worst case. I suppose that the real function which will need to be overwritten will not be the 'create' itself, but looking at the sources you could find the one.
The other solution, and I believe, a more elegant one, would be to create a trigger in the database. I am more in the PostgreSQL world, where I would use a 'CREATE RULE', but looking at the DB2 documentation I see that in DB2 there are 'INSTEAD OF' triggers. I hope this may be helpful.
I have achieved the same result by overriding ActiveRecord::Base#arel_attributes in my model:
Class Model < ActiveRecord::Base
##skip_attrs = [:attr1, :attr2]
def arel_attributes_values(include_primary_key = true, include_readonly_attributes = true, attribute_names = #attributes.keys)
skip_attrs = ##skip_attrs.map { |attr| [self.class.arel_table[attr] }
attrs = super(include_primary_key, include_readonly_attributes, attribute_names)
attrs.delete_if {|key, value| skip_attrs.include?(key) }
end
end
The attributes in the ##skip_attrs array will be ignored by ActiveRecord on both insert and update statements, as they both rely on arel_attributes_values for returning the list of attributes of the model.
A better solution would be: a patch on ActiveRecord::Base#arel_attributes along with a 'attr_ignore' macro similar to 'attr_readonly'.
cheers
I know this is very old, but I have been struggling with this very same issue. I have a database with a trigger that calculates an index value based on the max value within a key. I, too, want to prevent any ability to set the value in AR as it could throw off the index applied as rows are inserted.
CREATE TRIGGER incr_col_idx
AFTER INSERT ON fl_format_columns
FOR EACH ROW
BEGIN UPDATE fl_format_columns
SET idx = (SELECT coalesce(max(idx),-1) + 1
FROM fl_format_columns
WHERE fl_file_format_id = new.fl_file_format_id)
WHERE fl_file_format_id = new.fl_file_format_id AND name = new.name;
END;
I've tried a variety of things, but it always came back to overriding the setter directly.
# #raise ArgumentError when an attempt is made to set a value that is calculated in db
def idx=(o)
raise ArgumentError,'the value of idx is set by the db. attempts to set value is not allowed.' unless o.nil?
end
This will require catching the exception rather than interrogating the errors array, but that is what I ended up with. It does pass the following inspection:
context 'column index' do
it 'should prevent idx from being set' do
expect{FL_Format_Column.create(fl_file_format_id:-1,name:'test idx',idx:0)}.to raise_error(ArgumentError)
end
it 'should calculate idx relative to zero' do
x = FL_Format_Column.create(fl_file_format_id:-1,name:'test_idx_nil')
expect(x.errors[:idx].any?).to be false
expect(FL_Format_Column.last.idx).to be > -1
end
end

Resources