how do i get to retrieve my ratings something like this "['G','PG','PG-13','R']" from my database through my class method in my Movie class? My database contains a list of Movies table in which the row entails "title","ratings","description","release date".
To get ratings of all movies in a single array like you mentioned you simply use:
Movie.pluck(:ratings) #assuming column name ratings
This will give results like
['G','PG','PG-13','R']
If you also want to know that which movie has which ratings then, you can modify the code to following:
Movie.pluck(:id, :ratings)
Its result will be something like:
[[1,"PG"], [2,"PG-13"], [3,"G"]]
For more information visit this link
http://apidock.com/rails/ActiveRecord/Calculations/pluck
From the fact you've tagged rails and listed what sounds like a table structure I'm going to assume you're using Rails' ORM ActiveRecord with postgresql database right? If so, you could access your ratings by using the command Movie.pluck(:ratings). This should grab all the inserts in your ratings column for your Movies table and return an array of them. You will need to implement this in one of your MoviesController actions.
If you Ratings are stored in an Array then you would had to write a function to separate all the following: "['']". It would be much simple to create an enum or give you rating an ID so when you post a movie and want to give it a rating you can call it by calling its ID or enum value.
Please check this documentation about getting specific columns. In particular de pluck method.
http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck
So, you can do something like:
Movie.pluck(:ratings)
Other option is use a normal "query" structure:
#movies = Movie.select('ratings').where(...#some condition)
Related
I want to include an array which stocks the information of a model. Whenever an object of model A is created, the attribute name of this object is added in the array and this array won't be re-set when I restart the server. I try put the array to the associated model class and controller, but it does not work. Can you tell me how to do this?
I think what you want is every name of every ModelA that is stored in the DB?
According to #Leito, this would work:
ModelA.all.pluck(:name)
Maybe:
Model.all.uniq.pluck(:name), which translates to SELECT DISTINCT name FROM models
I have an HABTM association between two models, User and Conversation.
I want to be able to query the logged-in user's conversations (current_user.conversations), passing it another user's id, and have it return a conversation that is shared by both users, if one exists.
(an additional perk would be to have the query create one if one doesn't exist.)
The associations are working fine, so I can access the associated objects through instance variables like #user.conversations and #conversation.users, so I could go the long way and loop through each conversation object and search the user associations in each of them... But there must be an efficient way to construct this query.
What I would like to be able to do is something like current_user.conversations.where(conversation.users.exists?(id: #user_id)) or something like Conversation.find(users: {id: #user_id AND current_user.id}).
I imagine there is an obvious answer to this, and I've been searching around here for similar questions but haven't found any. After looking through the Rails API docs, I imagine that the solution I'm looking for involves .includes() in some way, but I can't get it working.
Any advice? Thanks.
Suppose you have two users #sender and #receiver, and there is one (or perhaps more) conversation between them. One possible way to query their shared conversations is by using the merge function in ActiveRecord. merge will select the intersection of conversations between between them:
#shared_conversations = #sender.conversations.merge(#receiver.conversations)
Note that the result will be a collection, not an individual conversation. In SQL this would translate to an INNER JOIN.
If you wanted to amend this query to create the conversation if it didn't exist, then you can use first_or_create. Like its name implies, first_or_create returns the first item in the collection. If the collection is empty, it will create a new object. You can pass it a block for further control over the newly created object:
#shared_conversations = #sender.conversations.merge(#receiver.conversations).first_or_create do |conversation|
conversation.title = "#{#sender.first_name}'s conversation"
end
You can find more details on merge in the Rails docs: http://apidock.com/rails/ActiveRecord/SpawnMethods/merge.
Try
current_user.conversations.includes(:users).where(user.id:current_user.id)
I have the following nested model relationship:
Countries (id, name)
Provinces (id, country_id, name)
Cities (id, province_id, name)
I have validates_uniqueness_of constraint on the name fields for each model in the relationship and a unique index on the name columns in the database.
I want to swap a new object created with the same name as an existing record at some point before it's validated. In other words, if a user attempts to add a city, province, country combination that has already been added, I want to country model to return a reference to the corresponding existing model records instead of failing validation before save.
I'm having trouble using the model callbacks (after_initialize, before_validation, etc.) and I wasn't able to get Country.find_or_initialize_by_name to work with the nested models... any suggestions?
What you are trying to do sounds pretty hard and will probably require you to know a lot of the internal implementation details of ActiveRecord::Base.
Instead, could you do something like this?
#country = Country.find_or_initialize_by_name(params[:name])
...
#country.save
EDIT:
ActiveRecord has find_or_create_by_XXX and find_or_initialize_by_XXX functions built in, so there is no need to add a function to the model. For more info see the "Dynamic attribute-based finders" section of http://api.rubyonrails.org/classes/ActiveRecord/Base.html
#user = User.new
#user.id returns nil but i need to know it before i save. Is it possible ?
YES you can!
I had the same question and investigated the docs.
The ability to solve this question is very related to your database type in fact.
Oracle and Postgresql do have useful functions to easily solve this.
For MySQL(oracle) or SkySQL(open-source) it seems more complicated (but still possible). I would recommend you avoid using these (MySQL/SkySQL) databases if you need advanced database tools.
First you must try to avoid this situation as much as possible in your application design, as it is dangerous to play with IDs before they get saved.
There may be situation where you don't have any other choice:
For instance when two tables are referencing themselves and for security reason you don't allow DELETE or UPDATE on these tables.
When this is the case, you can use the (PostgreSQL, Oracle) database nextval function to generate the next ID number without actually inserting a new record.
Use it in conjunction with the find_by_sql rails method.
To do this with postgreSQL and Rails for instance, choose one of your rails models and add a class method (not an instance method!).
This is possible with the "self" word at the beginning of the method name.
self tells Ruby that this method is usable only by the class, not by its instance variables (the objects created with 'new').
My Rails model:
class MyToy < ActiveRecord::Base
...
def self.my_next_id_sequence
self.find_by_sql "SELECT nextval('my_toys_id_seq') AS my_next_id"
end
end
When you generate a table with a Rails migration, by default Rails automatically creates a column called id and sets it as the primary key's table. To ensure that you don't get any "duplicate primary key error", Rails automatically creates a sequence inside the database and applies it to the id column. For each new record (row) you insert in your table, the database will calculate by itself what will be the next id for your new record.
Rails names this sequence automatically with the table name append with "_id_seq".
The PostgreSQL nextval function must be applied to this sequence as explained here.
Now about find_by_sql, as explained here, it will create an array containing new objects instances of your class. Each of those objects will contain all the columns the SQL statement generates. Those columns will appear in each new object instance under the form of attributes. Even if those attributes don't exist in your class model !
As you wisely realized, our nextval function will only return a single value.
So find_by_sql will create an array containing a single object instance with a single attribute.
To make it easy to read the value of this very attribute, we will name the resulting SQL column with "my_next_id", so our attribute will have the same name.
So that's it. We can use our new method:
my_resulting_array = MyToy.my_next_id_sequence
my_toy_object = my_resulting_array[0]
my_next_id_value = my_toy_object.my_next_id
And use it to solve our dead lock situation :
my_dog = DogModel.create(:name => 'Dogy', :toy_id => my_next_id_value)
a_dog_toy = MyToy.new(:my_dog_id => my_dog.id)
a_dog_toy.id = my_next_id_value
a_dog_toy.save
Be aware that if you don't use your my_next_id_value this id number will be lost forever. (I mean, it won't be used by any record in the future).
The database doesn't wait on you to use it. If somewhere at any time, your application needs to insert a new record in your my_table_example (maybe at the same time as we are playing with my_next_id_sequence), the database will always assign an id number to this new record immediately following the one you generated with my_next_id_sequence, considering that your my_next_id_value is reserved.
This may lead to situations where the records in your my_table_example don't appear to be sorted by the time they were created.
No, you can't get the ID before saving. The ID number comes from the database but the database won't assign the ID until you call save. All this is assuming that you're using ActiveRecord of course.
I had a similar situation. I called the sequence using find_by_sql on my model which returns the model array. I got the id from the first object of the arry. something like below.
Class User < ActiveRecord::Base
set_primary_key 'user_id'
alias user_id= id=
def self.get_sequence_id
self.find_by_sql "select TEST_USER_ID_SEQ.nextval as contact_id from dual"
end
end
and on the class on which you reference the user model,
#users = User.get_sequence_id
user = users[0]
Normally the ID is filled from a database sequence automatically.
In rails you can use the after_create event, which gives you access to the object just after it has been saved (and thus it has the ID). This would cover most cases.
When using Oracle i had the case where I wanted to create the ID ourselves (and not use a sequence), and in this post i provide the details how i did that. In short the code:
# a small patch as proposed by the author of OracleEnhancedAdapter: http://blog.rayapps.com/2008/05/13/activerecord-oracle-enhanced-adapter/#comment-240
# if a ActiveRecord model has a sequence with name "autogenerated", the id will not be filled in from any sequence
ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.class_eval do
alias_method :orig_next_sequence_value, :next_sequence_value
def next_sequence_value(sequence_name)
if sequence_name == 'autogenerated'
# we assume id must have gotten a good value before insert!
id
else
orig_next_sequence_value(sequence_name)
end
end
end
while this solution is specific to Oracle-enhanced, i am assuming the other databases will have a similar method that you could redefine.
So, while it is definitely not advised and you want to be absolutely sure why you would not want to use an id generated by a sequence, if it is needed it is most definitely possible.
It is why I love ruby and Ruby on Rails! :)
In Oracle you can get your current sequence value with this query:
SELECT last_number FROM user_sequences where sequence_name='your_sequence_name';
So in your model class, you can put something like this:
class MyModel < ActiveRecord::Base
self.sequence_name = 'your_sequence_name'
def self.my_next_id_sequence
get_data = self.find_by_sql "SELECT last_number FROM user_sequences where sequence_name='your_sequence_name'"
get_data[0].last_number
end
end
And finally, in controller you can get this value with this:
my_sequence_number = MyModel.my_next_id_sequence
So, there is no need to get your next value by using NEXTVAL and you won't lose you ID.
What you could do is User.max(id). which will return the highest ID in the database, you could then add 1. This is not reliable, although might meet your needs.
Since Rails 5 you can simply call next_sequence_value
Note: For Oracle when self.sequence_name is set, requesting next sequence value creates side effect by incrementing sequence value
I'm using Ruby on Rails and the paths_of_glory gem
I need to access the types of achievements that a user accomplishes in order to display a picture along with each particular achievement. When I try to access it via #user.achievements.type, I get an error that says that it wants to return "array" (as in achievements is an array) instead of actually returning the elements in the type column of my database.
Since every ruby object has a method called type, my call to access the type column of the database fails. When I try to change the entry in the table, the paths_of_glory gem says it needs a type column in order to function properly.
I'm not quite sure where to go from here in order to access that column in the database. Any suggestions?
Not entirely sure what you're asking here, but maybe this will help.
For the first thing, #user.achievements is an array because you have multiple achievements, and the type method is for individual elements of #user.achievements which is why that won't work just like that. You'll have to do something like this:
#user.achievements.each do |achievement|
# Do stuff here
end
Regarding the type column, type is a reserved column in Rails used specifically for Single Table Inheritance, where multiple Rails models use a single database table. So you can't access it directly. I assume that paths_of_glory uses STI in some manner. You can access the model's class with something like achievement.class, then if you want just the name of it you can try achievement.class.to_s.
#user.achievements.each do |achievement|
model = achievement.class # => MyAwesomeAchievementClass
#image = model.picture # You could write some method in the model like this
end