activerecord

Rails 3 ignore Postgres unique constraint exception

…衆ロ難τιáo~ 提交于 2019-12-10 02:41:45
问题 What's the correct way to rescue an exception and simply continue processing? I have an app that has Folders and Items, with a habtm relationship through a join table called folders_items. That table has a unique constraint ensuring that there are no duplicate item/folder combinations. If the user tries to add an item to the same folder several times, I obviously don't want the additional rows added; but I don't want to stop processing, either. Postgres automatically throws an exception when

ActiveRecord: Doesnt call after_initialize when method name is passed as a symbol

泪湿孤枕 提交于 2019-12-10 02:38:03
问题 I noticed that Rails doesn't trigger after_initialize callback when the callback symbol is passed as input. The code below doesn't work. class User < ActiveRecord::Base after_initialize :init_data def init_data puts "In init_data" end end The code below works. class User < ActiveRecord::Base def after_initialize init_data end def init_data puts "In init_data" end end Can somebody explain this behavior? Note 1 The ActiveRecord documentation says the following about after_initialize : Unlike

Negate ActiveRecord query scope

别来无恙 提交于 2019-12-10 02:29:05
问题 I have a slightly complicated scope on a model class Contact < ActiveRecord::Base scope :active, -> { where(inactive: false) } scope :groups, -> { where(contact_type: 2308) } scope :group_search, -> (query) do active.groups.where("last_name LIKE '%' + ? + '%'", query) end end For testing purposes, I want to make sure that all Contacts not returned by group_search are excluded for the right reasons. But to get that list, I have to load Contact.all - Contact.group_search('query') which runs two

Yii2: updateAll with multi conditions

北战南征 提交于 2019-12-10 02:24:34
问题 How to update all records by my condition? (my code is not work) $condition[] = ['>', 'position', $old_position]; $condition[] = ['<=', 'position', $new_position]; $condition[] = ['in', 'id', $ids]; Video::updateAll([ 'position' => new \yii\db\Expression('@a := @a + 1'), ], $condition); 回答1: You forgot the operator, you should simply try : $condition = ['and', ['>', 'position', $old_position], ['<=', 'position', $new_position], ['in', 'id', $ids], ]; Read more : http://www.yiiframework.com

ActiveRecord: can't use `pluck` after `where` clause with eager-loaded associations

喜欢而已 提交于 2019-12-10 02:03:59
问题 I have an app that has a number of Post models, each of which belongs_to a User model. When these posts are published, a PublishedPost model is created that belongs_to the relevant Post model. I'm trying to build an ActiveRecord query to find published posts that match a user name, then get the ids of those published posts, but I'm getting an error when I try to use the pluck method after eager-loading my associations and searching them with the where method. Here's (part of) my controller:

Rails model class method for collection of objects

喜欢而已 提交于 2019-12-10 01:45:36
问题 I'm having trouble writing class methods to use on collections of ActiveRecord objects. I've run into this issue twice in the last couple of hours, and it seems like a simple problem, so I know I'm missing something, but I haven't been able to find answers elsewhere. Example: class Order < ActiveRecord::Base belongs_to :customer scope :month, -> { where('order_date > ?', DateTime.now.beginning_of_month.utc) } def self.first_order_count map(&:first_for_customer?).count(true) end def first_for

ActiveRecord::UnknownAttributeError?

喜夏-厌秋 提交于 2019-12-10 01:34:32
问题 I just pushed an app to a production Heroku environment. Basically there is a Bus model and it has a seats attribute class Bus < ActiveRecord::Base attr_accessible :seats, # other attributes end Now I have a JavaScript frontend which POST's JSON for new buses to the buses#create action. ActiveRecord keeps encountering an error when I try to create a bus: : POST www.busables.com/buses dyno=web.1 queue=0 wait=5ms service=65ms status=500 bytes=728 : : ActiveRecord::UnknownAttributeError (unknown

How do you route [OPTIONS] in Rails?

自作多情 提交于 2019-12-10 01:28:47
问题 I am making a REST service in Rails. Here are my routes. resources :users match '/users', :controller => 'users', :action => 'options', :constraints => {:method => 'OPTIONS'} I am able to [GET] my users. I am trying to update my users and I get an error: ActionController::RoutingError (No route matches [OPTIONS] "/users/1"): When I run rake routes here are the routes that I am given: users GET /users(.:format) users#index POST /users(.:format) users#create new_user GET /users/new(.:format)

Query and order by number of matches in JSON array

感情迁移 提交于 2019-12-10 01:23:34
问题 Using JSON arrays in a jsonb column in Postgres 9.4 and Rails, I can set up a scope that returns all rows containing any elements from an array passed to the scope method - like so: scope :tagged, ->(tags) { where(["data->'tags' ?| ARRAY[:tags]", { tags: tags }]) } I'd also like to order the results based on the number of matched elements in the array. I appreciate I might need to step outside the confines of ActiveRecord to do this, so a vanilla Postgres SQL answer is helpful too, but bonus

yii2 ActiveRecord Find OrderBy with calculation

自作多情 提交于 2019-12-10 01:21:43
问题 Trying to fetch a description from my database. The query returns the result but I would like to order the result to only show the one with the highest vote. The vote should be calculated by the upvoted column subtracted by the downvoted column $description = UnitDescription::find() ->where(['id_unit' => $model->id]) ->orderBy([ 'upvoted - downvoted' => SORT_DESC //Need this line to be fixed ]) ->one(); I was hoping someone might have a way to write this part of the query - Thanks 回答1: You