activerecord

Activerecord associations as JSON with Grape

非 Y 不嫁゛ 提交于 2019-12-10 07:27:24
问题 Is there a simple way to return activerecord models with associations as JSON using the Grape microframework? get 'users' do User.includes(:address) end This snippet isn't working and User.includes(:address).to_json(include: :address) will get encoded twice as JSON. (To use the to_json method on my own doesn't feel right anyway) 回答1: You might want to use #as_json instead. So you can do User.includes(:address).as_json(include: :address) and that gives you a hash instead of a json string. 回答2:

Rails models in subfolders and relationships

戏子无情 提交于 2019-12-10 04:30:01
问题 I organized some of my rails models in folders which I am autoloading with config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**}')] I can use all models directly(e.g Image.first.file_name ) but when I try to access them through relationships, e.g. @housing.images.each do... with has_many: images I get the following error Unable to autoload constant Housing::HousingImage, expected /path/app/models/housing/image.rb to define it How do i get rails to use my models for the

How to convert activerecord results into an array of hashes including root

£可爱£侵袭症+ 提交于 2019-12-10 04:21:10
问题 Let's say you want to records = Model.all records.to_a.map{|m| m.serializable_hash(:root => true)} just like to_json(:root => true) does [ { "model": { "attribute_1": "value_1", "attribute_2": "value_2", } } ... ] 回答1: as_json records.as_json(:root => true) serializable_hash records.to_a.map() {|x| { x.class.model_name.element => x.serializable_hash() } } This will not work with nested objects though 来源: https://stackoverflow.com/questions/17090891/how-to-convert-activerecord-results-into-an

Rails includes query with conditions not returning all results from left table

大兔子大兔子 提交于 2019-12-10 04:12:09
问题 I have two tables, posts and images. Here is the relevant section from schema.rb: create_table "posts", force: true do |t| t.string "name" t.string "body" t.datetime "created_at" t.datetime "updated_at" end create_table "images", force: true do |t| t.integer "post_id" t.string "service_name" t.string "service_url" t.datetime "created_at" t.datetime "updated_at" end I want to find all the posts and join it with the images table, with a where clause on the images. I still want all of the posts

Can I execute a raw sql query, leverage prepared statements, and not use ActiveRecord::Relation::QueryAttribute?

非 Y 不嫁゛ 提交于 2019-12-10 04:12:07
问题 I want to do an upsert. Rails doesn't support this yet. The query is something like this: INSERT INTO foos (thing_id, bar_id) VALUES (1, 2) ON CONFLICT (thing_id, bar_id) DO NOTHING I can easily do this with self.class.connection.execute or exec_insert . But I want to also leverage prepared statements. I thought I can do this like so: thing_id = ActiveRecord::Relation::QueryAttribute.new("thing_id", thing.id, ActiveRecord::Type::Integer.new) bar_id = ActiveRecord::Relation::QueryAttribute.new

rails joins polymorphic association

浪尽此生 提交于 2019-12-10 04:10:08
问题 I have a ploymorphic association named Notifiable in a model named Notifiaction : module Notifiable def self.included(base) base.instance_eval do has_many :notifications, :as => :notifiable, :inverse_of => :notifiable, :dependent => :destroy end end end class Bill < ActiveRecord::Base include Notifiable end class Balance < ActiveRecord::Base include Notifiable end class Notification belongs_to :notifiable, :polymorphic => true belongs_to :bill, foreign_key: 'notifiable_id', conditions:

Rails accepts_nested_attributes_for always creates the nested models, but does not update them

China☆狼群 提交于 2019-12-10 04:03:28
问题 Given the following: class WebsitesController < ApplicationController # POST /websites/save # POST /websites/save.json def save Website.exists?(name: params[:website][:name]) ? update : create end # POST /websites # POST /websites.json def create @server = Server.find_or_create_by_name(params[:server_id]) @website = @server.websites.new(params[:website]) #etc... @website.save end # PUT /websites/1 # PUT /websites/1.json def update @website = Website.find_by_name(params[:website][:name]) #etc.

Rails: Eager loading as_json includes

一世执手 提交于 2019-12-10 04:01:24
问题 render :json => { "playlist" => playlist_description, "songs" => @playlist.songs.as_json(:include => {:playlist_songs => {:only => [:id, :position]}}) } The above code results in 1+N queries to the database, one to load playlist_songs for each song. The playlist is preloaded in @playlist. This is so slow, how can I optimize? 回答1: My guess: You're not eager-loading the playlist_songs at the moment. You're currently waiting until the as_json call - after which all the songs have been loaded -

Activerecord has_many :through through multiple models

你说的曾经没有我的故事 提交于 2019-12-10 03:59:46
问题 I'm trying to access all comments from a given user with user.comments . The query is to go through two different models, which likely both return results. My relations are set up as follow: class User < ActiveRecord::Base has_many :organisers has_many :participants has_many :comments, through: :participants / :organisers (see explenation below) end class Organiser < ActiveRecord::Base belongs_to :user end class Participant < ActiveRecord::Base belongs_to :user end class Comment <

how to call a active record named scope with a string

梦想与她 提交于 2019-12-10 03:07:19
问题 I'm sure I'm miss understanding the use of call but I thought I could do something like this. @case_studies = CaseStudy.call("some_named_scope") Where "some_named_scope" is also a named scope in CaseStudy . The reason why I need to use call is because I have named scopes that are the same names of the actions in the controller so I'm hopping to do something like this. @case_studies = CaseStudy.call(params[:action]) EDIT Forgive me, I just realized I was thinking about the send method, some