简体   繁体   中英

How can I show data from a db table that I'm already using else where in Rails

I've been going through the tutorials on rubyonrails.org so I have a model pulling data from the Articles table from my postgres db. I have my view displaying this table of records perfectly fine. However I'd like to know how I then add just the last Article record on the home page for instance. Do I 'query' the same Articles application record, or do I simply create an entirely new model, which doesn't seem that efficient as a site grows.

Do I generate complete new model such as rails generate model LastArticle ? I see that it looks like I can use article = Article.last or should this be lastarticle = Lastrticle.last and would I put this in the Model or a Controller?

Only been looking at RoR (coming from more of a php mysql background) for a few days so sorry if this is a jumbled question.

Models can be used anywhere in the rails application. In your home view controller you could do

@last_article = Article.last

And then reference @last_article in your home view.

You can even retrieve the record as part of the view...

<% last_article = Article.last %>

And then reference last_article in the same view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM