activerecord

ActiveRecord and sorting on association

我是研究僧i 提交于 2019-12-10 17:08:06
问题 I have a simple AR association like this: Question has_many :answers Answer belongs_to :question with `question_id` int(11) NOT NULL, `is_accepted` tinyint(1) DEFAULT NULL, in the answer. I'll have only one is_accpeted answer and am wondering if there is an easy to sort that to the top (just an order by)? thx Edit: here is my Answer class: class Answer < ActiveRecord::Base belongs_to :question end 回答1: the answer is in your schema `is_accepted` tinyint(1) For many databases, ActiveRecord

Using Rails Update to Append to a Text Column in Postgresql

空扰寡人 提交于 2019-12-10 16:56:58
问题 Thanks in advance for any help on this one. I have a model in rails that includes a postgresql text column. I want to append (i.e. mycolumn = mycolumn || newdata ) data to the existing column. The sql I want to generate would look like: update MyOjbs set mycolumn = mycolumn || newdata where id = 12; I would rather not select the data, update the attribute and then write the new data back to the database. The text column could grow relatively large and I'd rather not read that data if I don't

activerecord equivalent to SQL 'minus'

南楼画角 提交于 2019-12-10 16:53:07
问题 What's the rails way to subtract a query result from another? A database specific SQL example would be: SELECT Date FROM Store_Information MINUS SELECT Date FROM Internet_Sales 回答1: I'll throw this into the mix - not a solution, but might help with the progress: Best I can think of is to use NOT IN: StoreInformation.where('date NOT IN (?)', InternetSale.all) That's Rails 3 - Rails 2 would be: StoreInformation.all(:conditions => ['date NOT IN(?)', InternetSale.all]) But both of these will

How to do this group ActiveRecord query in postgres

北慕城南 提交于 2019-12-10 16:49:08
问题 I try to find over a 3M table, all the users who have the same username. I read something like this may do the trick. User.find(:all, :group => [:username], :having => "count(*) > 1" ) However since I'm using Postgres this return me ActiveRecord::StatementInvalid: PG::Error: ERROR: column "users.id" must appear in the GROUP BY clause or be used in an aggregate function . I'm trying something like this User.select('users.id, users.username').having("count(*) > 1").group('users.username') But

How can I cast an object to string for use with ActiveRecord queries?

二次信任 提交于 2019-12-10 16:48:42
问题 I have a User , which has a String email attribute. However, when I'm dealing with an email in my app, I find it desirable to first convert it to a (non-persisted) Email object, like so: class User < ActiveRecord::Base def email Email.new(self.read_attribute :email) end end Email#to_s and Email#to_str are both defined to be simply the original string (e.g., foo@bar.com ), so it's usually pretty transparent to the client whether they're dealing with an Email or a String . This works perfectly

Is there a way to serialize ActiveRecord's JSON properties using HashWithIndifferentAccess?

自古美人都是妖i 提交于 2019-12-10 16:36:57
问题 I am using ActiveRecord::ConnectionAdapters::PostgreSQLAdapter in a Rails application. Suppose I have a schema: create_table "foo", id: :bigserial, force: :cascade do |t| t.string "name" t.jsonb "data", null: false end Now suppose I run the following code: class Foo < ActiveRecord::Base self.table_name = :foo end my_foo = Foo.create!(:name => 'foobar', :data => {:a => 'hello'}) my_foo = Foo.where(:name => 'foobar').first! puts my_foo.data[:a] puts my_foo.data['a'] The output would be: # nil #

How to use ActiveModelSerializer with group_by?

ⅰ亾dé卋堺 提交于 2019-12-10 16:34:31
问题 I am using active_model_serializer in rails. I have two serializers: TodoSerializer and ProjectSerializer class TodoSerializer < ActiveModel::Serializer attributes :id, :project, :note has_one :project end and class ProjectSerializer < ActiveModel::Serializer attributes :id, :name has_many :todos end When I call render json: @todos Everything works great and I get the output I expect. However when I call: render json: @todos.group_by(&:project_id) It reverts back to another JSON call and it

Optimize difficult query (possibly with squeel)

大城市里の小女人 提交于 2019-12-10 16:16:31
问题 There is such code(using PublicActivity gem & Squeel) def index @activities = Activity.limit(20).order { created_at.desc } @one = @activities.where{trackable_type == 'Post'}.includes(trackable: [:author, :project]) @two = @activities.where{trackable_type == 'Project'}.includes trackable: [:owner] @activities = @one + @two end But it creates 8 SQL requests: SELECT "activities".* FROM "activities" WHERE "activities"."trackable_type" = 'Post' ORDER BY "activities"."created_at" DESC LIMIT 20

rails model attributes without corresponding column in db

岁酱吖の 提交于 2019-12-10 16:12:25
问题 I have some rails models which don't need any persistence, however I'd like rails to think the model actually has attributes x, y, z so when calling methods like to_json in the controller I get them included for free. For example, class ModelWithoutTableColumns << ActiveRecord::Base def x return "Custom stuff here" end There is no column x in the database for Table "ModelWithoutTable" (sorry for the slightly confusing name!) Anyone have an idea how to tackle this one? 回答1: Sounds like you

accept_nested_attributes_for :allow_destroy, :_destroy not working

一世执手 提交于 2019-12-10 16:11:31
问题 I have a Rails 4.1 application which is using a few notable technologies. Simple Form, Cocoon I'm having trouble destroying records which are nested attributes. Based on some lengthy research, I believe my code is correct, however I may be missing something silly. Model has_many :staff_services_joins, :dependent => :destroy has_many :services, :through => :staff_services_joins accepts_nested_attributes_for :staff_services_joins, :allow_destroy => true It's a little unorthodox, but I have two