How to Get Data from Database in Ruby

how to read data from database on Ruby

If you are using a relation DB like MySQL, Postgres or other you should use Active Record that RoR brings. It's a ORM and provides plenty of functionalities for interacting with DB, and it seems your are already using it. For querying data check this page on the guides.
http://guides.rubyonrails.org/active_record_querying.html

Some examples

Note.find(1) #get note with id=1
Note.find_by_note_type("sometype") #gets first found with note_type="sometype" (I think so)
Note.where("note_type = ?", "sometype") #gets all notes that have note_type="sometype"

retrieve data from database in rails?

If you have your associations defined with has_many, you don't need to use find that way

You just find the trainer:

@trainer = Trainer.find_by_id(params[id])

and then can access all it's events with

@trainer.events

For this to work you need in your trainer model:

has_many :events

in your Event model:

belongs_to :trainer

and a trainer_id column in the events table

edit

Naming the foreign_key column 'trainer' is a bad idea, it breaks Rails conventions and makes your life more difficult. You can tell Rails which column name to use like this:

has_many :events, :foreign_key => :trainer

and

belongs_to :trainer, :foreign_key => :trainer

but you should avoid this if any possible and change your migration instead and rebuild your database. This feature is mainly thought to allow using databases from old projects, not written in Rails.

In addition the other errors tell you, that there is no value in params[:id]. Do you have fixture data in the database?

To just see, if it works at all, you could start with

@trainer = Trainer.first

This would take the first trainer and then

@trainer.events

should work, if any events for this trainer exist. Then you can find out what's wrong with params[:id], most likely some link doesn't work properly, maybe your form is wrong or the routing to your controller has errors.

You are trying too many things at once, without having made sure, that the basics work. That's why we normally do test driven development in Ruby on Rails.

First set up the Trainer model. Then test it, make sure there are trainers by writing and loading fixtures, and that Rails can find them.

After that add the events model (and some fixture data again). If you don't explicitly write tests, then at least use the Rails console (i think it was the command script/console in Rails 2.x) to test. Only if you are 100% sure it works on the model level, start writing controllers. That way you have to handle only one error at any given moment.

How can I get data from database in ruby

Following should be Model code:

Class Window < ActiveRecord::Base
has_many :channels
end

class Channel < ActiveRecord::Base
belongs_to :window
end

In the console, do the following:

@window = Window.create(window: "This is window-1")

This will create a windows-instance and saves it into the database.

100.times do |index|
Channel.create(channel: Random.rand(1000),
data: Random.rand(1000),
window: @window)
end

This will create 100 Channel instances that belong to the earlier-created-window. Also, saves them to the database.

@window.channels will return the corresponding 100 channels.

This is how you write/insert record and read/fetch record.

Please do read http://edgeguides.rubyonrails.org/active_record_basics.html#create and http://edgeguides.rubyonrails.org/active_record_basics.html#read for better clarity and exploring futher,

Is there a way to fetch data in database from a Ruby-on-Rails models

ok , so i finally got it, i don't know if i should delete this thread or just tell how i did it. If it's inapropriate just tell me and i will delete this entire thread.

So here is how i did it, in the API controller i had to add my fetch so that the arguments (list) knows what i am talking about. @channel.days_limit

def index
podcasts = @channel.podcasts.published.list(params[:page], params[:items_per_page], params[:ordered_in], @channel.days_limit)

render json: Podcasts::Normalizer.normalize(podcasts, @channel.station.default_podcast_price)
end

then in the def list of the models, i added days_limit has argument

def list(page = nil, nb_items_per_page = 40, ordered_in = 'desc', days_limit)
ordered_in = ordered_in.in?(['asc', 'desc']) ? ordered_in : 'desc'
page.blank? ? by_days_limit(days_limit) : by_page(page, nb_items_per_page, ordered_in)
end

and finally in the scope of the models, i pass in the new argument

scope :by_days_limit, -> (days_limit) {with_tags.more_recent_than(Date.today - days_limit.days).ordered}

Now the user input from the app is passing to the models via the controller.

How to get data from database with specific combination of name

You might need SIMILAR TO

Try the below:

Topic.where('name SIMILAR TO ?', "%c\\d\\_c\\d\\_%")

If you are accepting more than one digits, Use the below pattern

Topic.where('name SIMILAR TO ?', "%c\\d+\\_c\\d+\\_%")

If you don't like escaping underscores, You can also use ~ for pattern matching as mentioned in the docs:

Topic.where('name ~ ?', ".*c\\d+_c\\d+_.*")

\d in the regular expression matches digits from 0 to 9

c*_c*_othername the othername is not compulsory. Some time the name is c5_c6 only so this type of names I also want to get

Please try the below pattern

 Topic.where('name ~ ?', ".*c\\d+_c\\d+(_.*)?$")

how to retrieve data from the database using the has_many association

I believe what you need is has_many ... :through

app/models/user.rb

class User < ApplicationRecord
# ...
has_many :messages, dependent: :destroy
has_many :message_pictures, through: :messages
end

app/controllers/messages_controller.rb

class MessagesController < ApplicationController
# ...

def index
@user = User.find(current_user.id)
@messages = @user.messages.paginate(page: params[:page])
@message_pictures = @user.message_pictures
end
end

has_many ... :through simplifies the retrieving of "nested" children records via "SQL JOINS", of which normally you would have done it in a longer (more explicit way) like the following (which also works):

class MessagesController < ApplicationController
# ...

def index
@user = User.find(current_user.id)
@messages = @user.messages.paginate(page: params[:page])
@message_pictures = MessagePicture.joins(message: :user).where(
messages: { # <-- this needs to be the table name, and not the association name, and is why it is in plural form
users: { # <-- this needs to be the table name, and not the association name, and is why it is in plural form
id: @user.id
}
}
)
end
end

Update: Alternative Solution

Looking back at your question, I have a feeling you'd only want @message_pictures that corresponds to @messages and not to all@user.messages, because I noticed you have pagination for the messages. I'll do it like this instead:

app/controllers/messages_controller.rb

class MessagesController < ApplicationController
# ...

def index
@user = User.find(current_user.id)

# the `includes` here prevents N+1 SQL queries, because we are gonna loop
# through each `message_picture` in each `message` record (see index.html.erb below)
@messages = @user.messages.includes(:message_pictures).paginate(page: params[:page])
end
end

app/views/messages/index.html.erb (example)

<h1>Messages:</h1>
<% @messages.each do |message| %>
<section>
<h2>Message:</h2>
<p><%= message.content %></p>

<h3>Message Pictures:<h3>
<div>
<% message.message_pictures.each do |message_picture| %>
<% message_picture.message_pictures.each do |message_picture_attachment| %>
<%= image_tag message_picture_attachment.url.to_s %>
<% end %>
<br>
<% end %>
</div>
</section>
<% end %>

^ Above assumes MessagePicture is using carrierwave. P.S. It looks to me there's something wrong with how you defined your models, because your message has many message_pictures, while each of the message_picture also has many attached message_picture carrierwave attachments (assuming you used the "multiple-file" upload set up for carrierwave because you used mount_uploader :message_pictures, PictureUploader instead of mount_uploader :message_picture, PictureUploader. The model problem I think is because it's like this: message < message_pictures < message_pictures attachments, but (depending on your use-case), it should probably be just like message < message_pictures - message_picture attachment, or just simply message < message_pictures attachments

How to pull and display data from database

You could include the whole table in the partial and render it inside your view (app/views/tasks/index.html.erb) for each one of your tables.

Example for app/views/tasks/_task.html.erb:

<table>
<tbody id="quadrant-<%= priority %>">
<% @tasks.each do |task| %>
<% if task.priority == priority %>
<tr>
<td><%= task.description %></td>
</tr>
<% end %>
<% end %>
</tbody>
</table>

Example for app/views/tasks/index.html.erb:

<h2>Priority 1</h2>
<%= render 'task', priority: 1 %>

<h2>Priority 2</h2>
<%= render 'task', priority: 2 %>

<h2>Priority 3</h2>
<%= render 'task', priority: 3 %>

<h2>Priority 4</h2>
<%= render 'task', priority: 4 %>

This will give you the flexibility to put each list wherever you want on your view, but this comes with a cost since you will iterate your task list 4 times (1 for each priority).

Although you could fix the this problem if you move the iteration out of the partial and include it in the view, inside a script that inserts each row on the correct table (quadrant).

Modified app/views/tasks/index.html.erb using JQuery:

<h2>Priority 1</h2>
<%= render 'task', priority: 1 %>

<h2>Priority 2</h2>
<%= render 'task', priority: 2 %>

<h2>Priority 3</h2>
<%= render 'task', priority: 3 %>

<h2>Priority 4</h2>
<%= render 'task', priority: 4 %>

<script type="text/javascript">
<% @tasks.each do |task| %>
$('#quadrant-<%= task.priority %>').append('<tr><td><%= task.description %></td></tr>');
<% end %>
</script>

Just replace hard-coded priority numbers (1..4) with your variables and this should, at least, point you in the right direction.



Related Topics



Leave a reply



Submit