Proper way to prevent ActiveRecord::ReadOnlyRecord?

后端 未结 4 874
执念已碎
执念已碎 2021-01-03 19:03

I\'m currently using Rails 2.3.9. I understand that specifying the :joins option in a query without an explicit :select automatically makes any re

4条回答
  •  别那么骄傲
    2021-01-03 19:16

    I believe that it would be customary and acceptable in this case to use :include instead of :join. I think that :join is only used in rare specialized circumstances, whereas :include is pretty common.

    If you're not going to be updating all of the active users, then it's probably wise to add an additional named scope or find condition to further narrow down which users you're loading so that you're not loading extra users & subscriptions unnecessarily. For instance...

    User.active.some_further_limiting_scope(:with_an_argument)
      #or
    User.active.find(:all, :conditions => {:etc => 'etc'})
    

    If you decide that you still want to use the :join, and are only going to update a small percentage of the loaded users, then it's probably best to reload just the user you want to update right before doing so. Such as...

    readonly_users = User.active
    # insert some other code that picks out a particular user to update
    User.find(readonly_users[@index].id).update_attributes(:etc => 'etc')
    

    If you really do need to load all active users, and you want to stick with the :join, and you will likely be updating most or all of the users, then your idea to reload them with an array of IDs is probably your best choice.

    #no need to do find_all_by_id in this case. A simple find() is sufficient.
    writable_users_without_subscriptions = User.find(Users.active.map(&:id))
    

    I hope that helps. I'm curious which option you go with, or if you found another solution more appropriate for your scenario.

提交回复
热议问题