开发者

How do I render data from model.rb into the index.html file?

开发者 https://www.devze.com 2023-04-03 04:06 出处:网络
I\'m building my first rails app and I have my HTML and CSS files set up in /public and models.rb in /models housing my code.

I'm building my first rails app and I have my HTML and CSS files set up in /public and models.rb in /models housing my code.

Right now the code is one Def that searches for the 5 most recent tweets mentioning me in the models.rb file.

I want to take those 5 tweets and style them in a certain way. I've never accessed data from one file to another so not quite sure how to get those tweets to appear in the index.html file.

Any help much appreciated.

require 'rubygems'
require 'twitter'

def search
  search = Twitter::Search.new
  search.containing("@twitter")开发者_Go百科.result_type("recent").per_page(5).each do |r|
     puts "#{r.from_user}: #{r.text}"
  end
end

search #calls search function

That is the code in models.rb, need to get that to show in index.html


First of all, you want to organize your files properly. You didn't mention controllers, but you'll need one for each type of 'thing' you want users to interact with. See: http://guides.rubyonrails.org/action_controller_overview.html

You want a file structure like this:

CSS in /public/stylesheets/whatever.css
HTML in /app/views/tweets/index.html.erb

Bear in mind I'm not familiar with your specific database structure, but in the tweets controller (stored in /app/controllers/tweets_controller.rb) you'd ideally want to be able to do this:

def index
    @tweets = @user.tweets.order("tweets.created_at DESC").limit(5)
end

Then in index.html.erb:

<% @tweets.each do |tweet| %>
    <div class="tweet">
        <%= @tweet.text %>
    </div>
<% end %>

This is the most detail I can give you from your question - you should read about the MVC structure in rails and most of all, take the time to get your project started/organized well. It'll save lots of headache for you in the future!

Best of luck.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号