Listing the Names of Associated Models

Listing the names of associated models

You want ActiveRecord::Reflection::ClassMethods#reflect_on_all_associations

So it would be:

 Article.reflect_on_all_associations

And you can pass in an optional parameter to narrow the search down, so:

 Article.reflect_on_all_associations(:has_many)

Article.reflect_on_all_associations(:belongs_to)

Keep in mind that if you want the list of all the names of the models you can do something like:

Article.reflect_on_all_associations(:belongs_to).map(&:name)

This will return a list of all the model names that belong to Article.

How to use a list of model names and variables for computing a table with its predictions?

When working with multiple models I prefer to work with a dataframe with list columns

example:

require(caret)
require(tidyverse)

dt <- data.frame(method = c('lm', 'glmnet')) %>%
mutate(model = map(method, ~ train(Sepal.Length ~ Petal.Length + Petal.Width,
data = iris,
method = .x))) %>%
mutate(predicted = map(model, predict))

dt %>% select(method,predicted) %>%
unnest()

The last line gives all predicted values of both models in a dataframe. This can easily be altered to give the value of only one prediction.

How to list related objects in Django Rest Framework

You can make use of PrimaryKeyRelatedField for this. First set related_name attribute to your foreign key.

university = models.ForeignKey(University, related_name='students')

And then change your serializer like this.

class UniversitySerializer(serializers.ModelSerializer):
students = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
class Meta:
model = University

Hope this helps :)

List of names of models in a Backbone.js Collection

You need to pluck the name attribute.

myAlbum.pluck('name');

There is no way to get an array like this:

['song1', 'song2', 'song3']

because names of variables are not available in program logic.

Update

When the tutorial writes this:

console.log( myAlbum.models ); // [song1, song2, song3]

It means that the array models is the same as if you were to write [song1, song2, song3], not as if you were to write ['song1', 'song2', 'song3']. The quotes are the differentiating factor.



Related Topics



Leave a reply



Submit