In my app I have 'patients' that have a preferred 'clinic'. On the patient is a 'preferred_clinic_id' and a belongs_to relationship. How do I specify in ember data that a patient belongs to a clinic through the preferred_clinic_id? Thanks for your help.
Here is the rails relationship:
belongs_to :preferred_clinic, class_name: 'Clinic`
App.Patient = DS.Model.extend({
preferred_clinic: DS.belongsTo('clinic', {inverse: null})
});
App.Clinic = DS.Model.extend({});
Related
I have two model as:
Customer:
has_many :products, :dependent => :destroy
accepts_nested_attributes_for :products, reject_if: proc { |attributes| attributes['product_id'].blank? }
Product:
belongs_to :customer
products controller:
def product_params
params.require(:product).permit(:name, :first_build)
end
customers controller:
def customer_params
params.require(:customer).permit(:first_build, :name, :product_id,
products_attributes: [:first_build, :customer_id])
end
So in the customers controller I do this
#customer.products.build(:first_build => true)
but I get this error
unknown attribute 'first_build' for Prodcut
but when I do this #customer.products.build(:name => "test product name")
it works perfectly without any error. One thing to note here, first_build is not a column in the products table.
If you want to pass attributes that are not in the table, you can create a "temporary" attribute which will not be stored in the table but will be available while the object is in memory.
class Product < ActiveRecord::Base
attr_accessor :first_build
...
end
I have three models, syndicates, users and activities. Each syndicate has many activities, and each activity has one user. My models look like this:
App.Syndicate = DS.Model.extend
activities: DS.hasMany('activity', async: true)
name: DS.attr 'string'
App.Activity = DS.Model.extend
syndicate: DS.belongsTo('syndicate')
user: DS.belongsTo('user', async: true)
App.User = DS.Model.extend
activities: DS.hasMany('activity', async: true)
I display the activities using
article#lead
h1= model.name
each activity in model.activities
p
= activity.id
p
= activity.user.name
Looking at syndicate/1, I get a list of the activities for that syndicate, with a user name for each activity, but each user is triggering a separate request to the api - very slow and expensive. I want to know if I cant request the users in a single query.
My reading suggested I could simply set 'coalesceFindRequests' to true, but this didn't work for me
DS.RESTAdapter.reopen
namespace: 'api/v1'
coalesceFindRequests: true
App.Store = DS.Store.extend(
serializer: DS.RESTSerializer.extend
primaryKey: (type) ->
'_id';
)
App.ApplicationAdapter = DS.ActiveModelAdapter.extend()
My route
App.SyndicateRoute = Ember.Route.extend
model: (params) ->
console.log params.syndicate_id
#store.find 'syndicate', params.syndicate_id
Any pointers on what I'm doing wrong?. I'm very new to ember.
Thanks :)
You can, side load the related data for the aggregate.
http://emberjs.com/guides/models/the-rest-adapter/
I have a user, user_profile and profile_type models. A user has_many user_profiles, a user_profile belongs_to a user and belongs_to a profile_type and a profile_type has_many user_profiles.
I have been reading on how to get this work but I am having problems figuring this out and any help would be much appreciated.
I know I could do this with SQL with a statement like this (freehand SQL, excuse mistakes), but I want to use ActiveRecord.
Select up.id, u.user_id, pt.connection_type
from user u
join user_profile up
on u.user_id = up.user_id
join profile_type pt
on pt.profile_type_id = up.profile_type_id
where u.username = "test"
I want to return nested user_profile objects for an associated user but I want the user_profile object to contain the profile_type.connection_type instead of the profile_type.profile_id.
Currently, if I do this,
user.user_profiles.all
add then iterate through the nested user_profiles that are returned, this is my output:
{
:id
:user_id
:profile_type_id
}
What I want is:
{
:id
:user_id
:profile_type.connection_type (instead of profile_type.profile_type_id)
}
User Model
class User < ActiveRecord::Base
has_many :user_profiles, autosave: true
has_many :account_settings, autosave: true
end
User_Profile Model
class UserProfile < ActiveRecord::Base
belongs_to :user
belongs_to :profile_type
end
User Profile Type Model
class ProfileType < ActiveRecord::Base
has_many :user_profiles
end
Try this:
user.account_settings.select("profile_type.*, profile_type.connection_type").all
I was able to figure out how to do this using Grape.
Since the association was already created, I can use Grape entities to expose what I needed out of the associations. It works seamlessly and I hope this helps anyone else who is having a similar problem.
To get what I was looking for, I needed to gather all user_profiles
userprofiles = user.user_profiles.all
Then, I presented this using Grape
present :user_profile_settings, userprofiles, with: API::V1::Entities::UserProfile
And, here is what my entities looked like:
class UserProfile < Grape::Entity
expose :profile_type, using: ProfileTypeEntity
end
class ProfileTypeEntity < Grape::Entity
expose :connection_type
end
If I have the following models in Rails, how would I represent this in Ember/Ember Data?
class Attachment < ActiveRecord::Base
belongs_to :user
belongs_to :attachable, polymorphic: true
end
class Profile < ActiveRecord::Base
belongs_to :user
has_one :photo, class_name: 'Attachment', as: :attachable
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :attachments, as: :attachable
end
References I've found are the relevant ember-data pull request, the ember-data tests for polymorphic relationships, and this related question but it's difficult to work out a canonical example from them.
I now use two different ways of working with rails-style "polymorphic" models. I have updated the code below to show both uses.
Attachment model: This is "polymorphic" on the Rails side but is always "embedded" on the Ember side. The reason for this is that I currently only need to save/update attachments along with their associated model.
Comment model: This is polymorphic on both the Rails side and the Ember side.
I have also included code for the Post model as it can have multiple attachments and multiple comments.
Rails code:
class Attachment < ActiveRecord::Base
belongs_to :user
belongs_to :attachable, polymorphic: true
end
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :commentable, polymorphic: true
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :attachments, as: :attachable
has_many :comments, as: :commentable
end
class ApplicationSerializer < ActiveModel::Serializer
embed :ids, include: true
end
class AttachmentSerializer < ApplicationSerializer
attributes :id, :url, :errors
has_many :comments
end
class CommentSerializer < ApplicationSerializer
attributes :id, :body, :created_at, :commentable_id, :commentable_type
has_one :user
end
class PostSerializer < ApplicationSerializer
attributes :id, :title, :body, :posted_at, :errors
has_one :user
has_many :attachments, embed: :objects, include: true
has_many :comments
end
class Api::V1::PostsController < Api::V1::BaseController
before_filter :auth_only!, only: :create
def create
# clean / capture ember-data supplied arguments
params[:post].delete(:user_id)
attachments_params = params[:post].delete(:attachments)
#post = current_user.posts.new(params[:post])
process_attachments(attachments_params)
if #post.save
render json: #post, status: 201
else
warden.custom_failure!
render json: #post, status: 422
end
end
protected
def process_attachments(attachments_params)
return unless attachments_params.present?
attachments_params.each do |attachment_params|
# ignore ember-data's additional keys
attachment_params.delete(:created_at)
attachment_params.delete(:user_id)
attachment = #post.attachments.new(attachment_params)
attachment.user = current_user
end
end
end
Ember code:
DS.RESTAdapter.configure 'App.Post',
alias: 'Post'
DS.RESTAdapter.map 'App.Post',
attachments: { embedded: 'always' }
App.Store = DS.Store.extend
adapter: DS.RESTAdapter.create
namespace: 'api/v1'
App.Comment = App.Model.extend
user: DS.belongsTo('App.User')
commentable: DS.belongsTo('App.Commentable', { polymorphic: true })
body: DS.attr('string')
createdAt: DS.attr('date')
App.Commentable = App.Model.extend
comments: DS.hasMany('App.Comment')
App.Attachment = App.Commentable.extend
user: DS.belongsTo('App.User')
url: DS.attr('string')
App.Post = App.Commentable.extend
user: DS.belongsTo('App.User')
attachments: DS.hasMany('App.Attachment')
title: DS.attr('string')
body: DS.attr('string')
postedAt: DS.attr('date')
App.PostFormOverlayController = App.OverlayController.extend
# 'files' attribute is set by a widget that wraps the filepicker.io JS
updateAttachments: (->
attachments = #get('attachments')
attachments.clear()
#get('files').forEach (file) =>
attachment = App.Attachment.createRecord({fpFile: file})
attachments.addObject(attachment)
).observes('files')
App.CommentNewController = App.ObjectController.extend
# this should be instantiated with it's model set to the commentable
# item. eg. `{{render 'comment/new' content}}`
save: ->
transaction = #get('store').transaction()
comment = transaction.createRecord App.Comment,
body: #get('body')
commentable: #get('model')
comment.one 'didCreate', #, ->
#set('body', null)
transaction.commit()
Unfortunately my Rails code has become a little polluted with ember-data specific oddities as it tries to send back all the attributes that are defined on the models. (Note: There is an open proposal for read-only attributes that would solve the params pollution issue)
If anyone knows a better way to approach any of the above please let me know!
NB: I'm a little concerned that having models extend from App.Commentable will prevent me from having multiple polymorphic attachments on a model, I may need to look for a different way of handling that.
The Comment part of Kevin Ansfield's answer (didn't use the Post part) works as of Ember 1.3.0-beta / Ember Data 1.0.0-beta.4 except for the rails serializer, which should now be:
class CommentSerializer < ActiveModel::Serializer
attributes :id, :body, :created_at, :commentable_id, :commentable_type
has_one :user
def attributes
data = super
data[:commentable] = {id: data[:commentable_id], type: data[:commentable_type]}
data.delete(:commentable_type)
data.delete(:commentable_id)
data
end
I am having an issue with trying to save many to many relationships in Ember.js using ember-data and rails. The association works fine on the ember side of things, however when I try to commit the transaction it will not include the list of new associations when submitting to rails. Any help would be much appreciated, I've been tearing out my hair trying to find an example application that does something this simple on github but I can't seem to find one.
Here is a dumbed down version of my Ember code:
App.Store = DS.Store.extend
revision: 11
adapter: DS.RESTAdapter.create
url: '/api'
App.Router.map ->
#resource 'rosters'
#resource 'users'
App.User = DS.Model.extend
rosters: DS.hasMany 'App.Roster'
App.Roster = DS.Model.extend
users: DS.hasMany 'App.User'
App.RostersEditRoute = Ember.Route.extend
setupController: (controller, model) ->
controller.set 'users_list', App.User.find()
App.RostersEditView = Ember.View.extend
userCheckbox: Em.Checkbox.extend
checkedObserver: ( ->
users = #get 'roster.users'
if #get 'checked'
users.addObject #get 'user'
else
users.removeObject #get 'user'
#get('controller.store').commit()
).observes 'checked'
Edit form:
each user in users_list
label.checkbox
view view.userCheckbox rosterBinding="current_roster" userBinding="user" | #{user.full_name}
Rails Backend (Using Inherited Resources and Active Model Serializer gems):
class User < ActiveRecord::Base
has_many :rosters_users
has_many :rosters, through: :rosters_users
accepts_nested_attributes_for :rosters
end
class RostersUser < ActiveRecord::Base
belongs_to :user
belongs_to :roster
end
class Roster < ActiveRecord::Base
has_many :rosters_users
has_many :users, through: :rosters_users
accepts_nested_attributes_for :users
end
module Api
class RostersController < BaseController
end
end
module Api
class UsersController < BaseController
end
end
module Api
class BaseController < ActionController::Base
inherit_resources
respond_to :json
before_filter :default_json
protected
# Force JSON
def default_json
request.format = :json if params[:format].nil?
end
end
end
class UserSerializer < BaseSerializer
has_many :rosters, embed: :ids
end
class RosterSerializer < BaseSerializer
has_many :users, embed: :ids
end
So like I said, the association works fine on Ember but rails doesn't seem to be getting the new association data. When I check out the XHR tab in the web inspector, I see it only sent this:
Request Payload
{"roster":{"created_at":"Thu, 21 Mar 2013 23:16:02 GMT","team_id":"1"}}
And I am returned with a 204 no content error because nothing changed.
Despite the fact that it's possible to set up matching hasMany relationships, Ember Data doesn't actually support many to many relationships yet (see this issue). What you can do for now is decompose the relationship using a membership model.
App.User = DS.Model.extend
rosterMemberships: DS.hasMany 'App.RosterMembership'
App.RosterMembership = DS.Model.extend
user: DS.belongsTo 'App.User'
roster: DS.belongsTo 'App.Roster'
App.Roster = DS.Model.extend
rosterMemberships: DS.hasMany 'App.RosterMembership'
Now you can use createRecord() and deleteRecord() with the membership model to add and delete relationships.
Unfortunately, in this example, it's not so easy to bind to the collection of rosters for a particular user. One work-around is as follows:
App.User = DS.Model.extend
rosterMemberships: DS.hasMany 'App.RosterMembership'
rosters: ( ->
#get('rosterMemberships').getEach('user')
).property 'rosterMemberships.#each.relationshipsLoaded'
App.RosterMembership = DS.Model.extend
user: DS.belongsTo 'App.User'
roster: DS.belongsTo 'App.Roster'
relationshipsLoaded: ( ->
#get('user.isLoaded') and #get('roster.isLoaded')
).property 'user.isLoaded', 'roster.isLoaded'
If you bind to user.rosters, then your template should update when relationships are created or destroyed.
Alternate solution:
App.Roster = DS.Model.extend
users_map: DS.attr('array')
users: DS.hasMany 'App.User'
users_change: (->
#set('users_map', #get('users').map((el) -> el.id).toArray())
).observes('users.#each')
to server in POST data will sending array of users ids