MZaragoza
MZaragoza

Reputation: 10111

Association with scope in Ruby on Rails

I have a Ruby on Rails application in which I have licenses, items that can be licensed and a table that lists the two (Which items in what quantity are present in the license?). Analogously to the items in a shopping cart.

Some of the items will no longer be marketed, but I intend to keep them in the database. I then created a soft-delete and used a default scope for the template and for the relationships. But when I try to change existing records using the related template, I get an exception: ActiveRecord :: ReadOnlyRecord

My templates look like this:

class Item <ActiveRecord :: Base
  default_scope {where (deleted: false)}
end

class LicenseItem <ActiveRecord :: Base
  belongs_to: license, touch: true
  belongs_to: item
end

class License <ActiveRecord :: Base
  has_many: license_items,
          -> {joins (: item) .where (items: {deleted: false})},
          dependent:: destroy
end

In this way:

pry (main)> License.find (0) .license_items [0] .readonly?
=> true

Is there any way to make this relationship not just reading?

I have already tried to add readonly (false) at the end of the has_many scope toLicense without success.

Upvotes: 4

Views: 507

Answers (1)

MZaragoza
MZaragoza

Reputation: 10111

According to this thread in GitHub, this is a Rails 4.0 bug, which has been fixed in version 4.0.1. Updating your Rails, you can include readonly (false) in your scope and it will work:

class License <ActiveRecord :: Base
    has_many: license_items,
          -> {joins (: item) .where (items: {deleted: false}). readonly (false)},
          dependent:: destroy
end

To update the Rails version, edit your Gemfile and then runbundle update.

In the latter case, if you can not update the Rails version, you can pass the readonly: false option to thefind (not recommended) method:

License.find (1) .license_items.find (1, readonly: false) .update_attributes (amount: 5)

Upvotes: 5

Related Questions