Why can I not save tweets into the database? - ruby

I want to save the tweets into the database, but it doesn't work! I'm using the twitter gem.
My controller:
class TweetsController < ApplicationController
def save_tweets_into_database
#tweets = Twitter.search("#em2012" "#Italy" "#Spain", :lang => "en", :rpp => 25).results
#tweets.each do |tweet|
#tweet = tweet
#tweet.create
end
end
end
My Model
require "rubygems"
require "twitter"
class Tweet < ActiveRecord::Base
end
My view
<% #title = "liste" %>
<h2>Liste der Tweets über das EM-Finale</h2>
<ul>
<% #tweets.each do |tweet| %>
<li><%= tweet %></li>
<% end %>
</ul>
my routes
Em2012tweet::Application.routes.draw do
match '/save_tweets', to: 'tweets#save_tweets_into_database'
end
This error is displayed:
undefined method `create' for Twitter::Status:0x007fac9c80a160
Rails.root: /Users/xyz/Desktop/Workspace/em2012tweet
app/controllers/tweets_controller.rb:7:in `block in save_tweets_into_database'
app/controllers/tweets_controller.rb:5:in `each'
app/controllers/tweets_controller.rb:5:in `save_tweets_into_database'

save the tweets into the database
In Rails, following REST convention, index action is associated with simply displaying all the objects of a model already stored in database. And this is actually what you did with the code as well. Your index action isn't doing anything that will save the tweets into the database.
I don't think you are trying to save tweets here. You are trying to simply display them. Try this if you want to simply display tweets in index view file.
def index
#tweets = Twitter.search("#em2012" "#italy" "#spain", :lang => "en", :rpp => 25).results
end
If you want to save tweets, create an action like this.
def save_tweets_into_database
#tweets = Twitter.search("#em2012" "#italy" "#spain", :lang => "en", :rpp => 25).results
#tweets.each do |tweet|
Tweet.save(tweet)
end
end

tweets_controller.rb:
class TweetsController < ApplicationController
def save_tweets_into_database
#tweets = Twitter.search("#em2012" "#Italy" "#Spain", :lang => "en", :rpp => 25)
#tweets.each do |tweet|
Tweet.create(twitter_tweet: tweet)
end
end
end
tweet.rb:
class Tweet < ActiveRecord::Base
serialize :twitter_tweet
end
Note that this requires you have a migration where a tweets table is created with a text column named 'twitter_tweet', e.g.
class CreateTweets < ActiveRecord::Migration
def change
create_table :tweets do |t|
t.text :twitter_tweets
t.timestamps
end
end
end
This will allow you to call save_tweets_into_database and save the 25 returned tweets into the database. This isn't a very good strategy, as you are serializing each of the Twitter::Status objects and storing them as YAML in your database. This means you lose the ability to use all the nice ActiveRecord helpers, and instead must deserialize all of the objects you want to work with before actually using them. A better strategy would be to create an ActiveRecord object that has the same attributes as those in the Twitter::Status object you wish to save. Then you can map the fetched Twitter::Status objects to the new ActiveRecord Tweet objects and retain all the benefits of using ActiveRecord.
I'll not say anything about your routing structure, other than it definitely doesn't appear to be following the 'Rails' way, which, from experience, typically leads to quite a few headaches.

Related

rails buttons click counter

This is another I'm-totally-new-to-Ruby-please-have-mercy situation.
So i'm trying to figure out how to make a database of all my buttons to save the click count each time they're clicked. I started a new rails to try it out and generated a model Buttonand a controller buttons index
route.rbs
Rails.application.routes.draw do
resources :buttons
root 'buttons#index'
end
migration
class CreateButtons < ActiveRecord::Migration[5.0]
def change
create_table :buttons do |t|
t.integer :clicks
t.timestamps
end
end
end
buttons_controller
class ButtonsController < ApplicationController
def index
#button = Button.find(1)
end
def doit
#button = Button.find(1)
#newcount = #button.clicks + 1
Button.find(1).update_attributes(:clicks => #newcount)
end
end
Now.. i need to trigger the doit method.. is it possible to trigger a non CRUD operation ?
i tried this but it doesn't seem to work
index.html.erb
<h1>Hello, This is button and my click are :</h1>
<h1><%= #button.clicks %></h1>
<%= link_to 'click me', method: :doit %>
I know there's something I'm not getting here...
Ruby have been doing so much magic that I can't do a simple ruby method.. it have been really hard for me getting the part were methods are taking place without calling them by name..
Specially when I trigger a delete method and the destroy method is triggered by that.. I really need to get used to this too-much-magic coding
Several things to improve, I think. Please get back to me if something is not working (I did not run the code)
Make your index action list all the buttons
Controller:
def index
#buttons = Button.all
end
View:
<h1>These are all my buttons</h1>
<% #buttons.each do |button| %>
<%= link_to("Button #{button.id}", button_votes_path(button), method: :post) %>
<% end %>
It's common to have index show a list of resources.
Only create the routes you need, make increment a separate action
I'd chose to call it "vote". You could also call it "clicks" or "presses" or whatever.
resources :buttons, only: [:index] do
resources :votes, only: [:create]
end
Add the votes controller
class VotesController < ApplicationController
def create
button = Button.find(params[:id])
button.clicks += 1
button.save
redirect_to buttons_path
end
end
No error handling here. So this is just to get you started.
For the next steps I suggest you follow a tutorial or start with simpler stuff.

how to display json and parse json in ruby using httparty

I am working on a food app in ruby on rails which requires to get calorie value of food item from food api.In my controller i am getting the JSON response but i am unable to parse and display the calorie value of food item in a index.html.erb file here is my controller code.
require 'rubygems'
require 'httparty'
class FoodsController < ApplicationController
def index
#foods = Food.all
end
def show
#food = Food.find(params[:id])
end
def new
#food = Food.new
end
def edit
#food = Food.find(params[:id])
end
def create
#food = Food.new(food_params)
#response = HTTParty.get('http://api.nutritionix.com/v1_1/search/'+#food.name+'?fields=item_name%2Citem_id%2Cbrand_name%2Cnf_serving_size_unit%2Cnf_calories%2Cnf_total_fat&appId=696d1ad4&appKey=aec2c4766d40d7f6346ed89d5d82fe75')
#http_party_json = JSON.parse(#response.body)
if #food.save
redirect_to foods_path
else
render 'new'
end
end
def update
#food = Food.find(params[:id])
if #food.update(food_params)
redirect_to #food
else
render 'edit'
end
end
def destroy
#food = Food.find(params[:id])
#food.destroy
redirect_to foods_path
end
private
def food_params
params.require(:food).permit(:name, :quantity)
end
end
Any suggestions are highly welcome as i am newbie on stackoverflow so dont know proper editing forgive please! help me how to display calorie value in html page
You can add a new function to Food model to get you the Calorie:
class Food
def calorie
response = HTTParty.get("http://api.nutritionix.com/v1_1/search/#{self.name}?fields=item_name%2Citem_id%2Cbrand_name%2Cnf_serving_size_unit%2Cnf_calories%2Cnf_total_fat&appId=696d1ad4&appKey=aec2c4766d40d7f6346ed89d5d82fe75")
json = JSON.parse(response.body)
end
end
and then simply in your index.erb if you loop over foods collection you do the following:
<% #foods.each do |food| %>
<%= food.name %>
<%= food.calorie %>
<% end %>
but in that case performance will not be good, as you do remote access for each item each time you display data, so as calorie value is always the same for same food, then after its created you can do remote query and store the calorie to calorie attribute in your Food model
You can do the following:
class Food < ActiveRecord::Base
before_create :set_calorie
private
def set_calorie
response = HTTParty.get("http://api.nutritionix.com/v1_1/search/#{self.name}?fields=item_name%2Citem_id%2Cbrand_name%2Cnf_serving_size_unit%2Cnf_calories%2Cnf_total_fat&appId=696d1ad4&appKey=aec2c4766d40d7f6346ed89d5d82fe75")
self.calorie = JSON.parse(response.body)
end
end

Rails 3 NoMethodError (undefined method `unserialized_value' for "--- []\n":String):

I am using Rails 3.2.13 and postgress.
I am getting below error only in production server
NoMethodError (undefined method `unserialized_value' for "--- []\n":String):
app/controllers/blogs_controller.rb:159:in `content_generators'
I am serializing Array to store it in db. Below is code.
Controller
class BlogsController < ApplicationController
def content_generators
#blog = Blog.find(params[:id])
#users = #blog.content_generators.map do |id|
User.find(id)
end
end
end
Model
class Blog < ActiveRecord::Base
serialize :post_access, Array
serialize :content_generators, Array
attr_accessible :post_access, :content_generators
end
Migration
class AddContentgeneratorsToBlog < ActiveRecord::Migration
def change
add_column :blogs, :content_generators, :string, :default => [].to_yaml
end
end
I have already used serialization. You can see post_access is serialized. And that works perfect.
But now when I added another column content_generators it starts breaking.
Thanks for your help in advance.
Since you are using postgresql I strongly recommend using the built in array functionality:
# Gemfile
gem 'postgres_ext'
class MyMigration
def change
add_column :my_table, :that_array_column, :text, array: true, default: []
end
end
Then remove the serialize calls in your model and that's it. PG serialized array's behave exactly the same as YAML serialized ones on the model, except the db supports some query methods on them.

How to display contents from a sequel database connection in the view file in Ruby?

I am trying to retrieve data from a PostgreSQL database with Sequel in Sinatra.
DB = Sequel.connect('postgres://connection_data')
items = DB[:items]
Then I try to get an entry with a specific ID:
get '/:id' do
#item = items.filter(:id => params[:id])
erb :edit
end
In my edit view I would like to display the content of the #item variable. The problem is that I don´t know how to get for example the ID.
<% if #item %>
Do something
<% else %>
<p>Item not found.</p>
<% end %>
I tried using #item.id and #item[:id] but both don´t work. I get an error undefined method 'id' for #<Sequel::Postgres::Dataset:0x007fac118b7120>. What would be the right way to retrieve the values from the #item variable?
#item = items.filter(:id => params[:id]) returns a dataset. If you want a single item, you should do: #item = items.first(:id => params[:id].to_i)
Also #item.id is probably not want you want. Given that items = DB[:items], you are using a plain dataset and then #item = items.first(:id => params[:id].to_i) is going to give you a hash. You need to do #item[:id] to get the item's id.
You may want to look at using models instead:
# model file
class Item < Sequel::Model; end
# sinatra code
#item = Item[params[:id].to_i]
# template
#item.id
Actually #item.id is the right way. The only problem I can see in your code is
#item = items.filter(:id == params[:id])
which should be
#item = items.filter(:id => params[:id].to_i)
EDIT:
Try this:
#item = items.where(:id => params[:id].to_i)
#item.select(:id) #to embed
params[:id] is giving a string, so convert it to an integer.

ActiveRecord::Base Without Table

This came up a bit ago ( rails model attributes without corresponding column in db ) but it looks like the Rails plugin mentioned is not maintained ( http://agilewebdevelopment.com/plugins/activerecord_base_without_table ). Is there no way to do this with ActiveRecord as is?
If not, is there any way to get ActiveRecord validation rules without using ActiveRecord?
ActiveRecord wants the table to exist, of course.
This is an approach I have used in the past:
In app/models/tableless.rb
class Tableless < ActiveRecord::Base
def self.columns
#columns ||= [];
end
def self.column(name, sql_type = nil, default = nil, null = true)
columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default,
sql_type.to_s, null)
end
# Override the save method to prevent exceptions.
def save(validate = true)
validate ? valid? : true
end
end
In app/models/foo.rb
class Foo < Tableless
column :bar, :string
validates_presence_of :bar
end
In script/console
Loading development environment (Rails 2.2.2)
>> foo = Foo.new
=> #<Foo bar: nil>
>> foo.valid?
=> false
>> foo.errors
=> #<ActiveRecord::Errors:0x235b270 #errors={"bar"=>["can't be blank"]}, #base=#<Foo bar: nil>>
Validations are simply a module within ActiveRecord. Have you tried mixing them into your non-ActiveRecord model?
class MyModel
include ActiveRecord::Validations
# ...
end
I figure the more answers the better since this is one of the first results in google when searching for "rails 3.1 models without tables"
I've implements the same thing without using ActiveRecord::Base while including the ActiveRecord::Validations
The main goal was to get everything working in formtastic, and below I've included a sample payment that will not get saved anywhere but still has the ability to be validated using the validations we all know and love.
class Payment
include ActiveModel::Validations
attr_accessor :cc_number, :payment_type, :exp_mm, :exp_yy, :card_security, :first_name, :last_name, :address_1, :address_2, :city, :state, :zip_code, :home_telephone, :email, :new_record
validates_presence_of :cc_number, :payment_type, :exp_mm, :exp_yy, :card_security, :first_name, :last_name, :address_1, :address_2, :city, :state
def initialize(options = {})
if options.blank?
new_record = true
else
new_record = false
end
options.each do |key, value|
method_object = self.method((key + "=").to_sym)
method_object.call(value)
end
end
def new_record?
return new_record
end
def to_key
end
def persisted?
return false
end
end
I hope this helps someone as I've spent a few hours trying to figure this out today.
UPDATE: For Rails 3 this can be done very easy. In Rails 3+ you can use the new ActiveModel module and its submodules. This should work now:
class Tableless
include ActiveModel::Validations
attr_accessor :name
validates_presence_of :name
end
For more info, you can check out the Railscast (or read about it on AsciiCasts) on the topic, as well as this blog post by Yehuda Katz.
OLD ANSWER FOLLOWS:
You may need to add this to the solution, proposed by John Topley in the previous comment:
class Tableless
class << self
def table_name
self.name.tableize
end
end
end
class Foo < Tableless; end
Foo.table_name # will return "foos"
This provides you with a "fake" table name, if you need one. Without this method, Foo::table_name will evaluate to "tablelesses".
Just an addition to the accepted answer:
Make your subclasses inherit the parent columns with:
class FakeAR < ActiveRecord::Base
def self.inherited(subclass)
subclass.instance_variable_set("#columns", columns)
super
end
def self.columns
#columns ||= []
end
def self.column(name, sql_type = nil, default = nil, null = true)
columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
end
# Overrides save to prevent exceptions.
def save(validate = true)
validate ? valid? : true
end
end
This is a search form that presents an object called criteria that has a nested period object with beginning and end attributes.
The action in the controller is really simple yet it loads values from nested objects on the form and re-renders the same values with error messages if necessary.
Works on Rails 3.1.
The model:
class Criteria < ActiveRecord::Base
class << self
def column_defaults
{}
end
def column_names
[]
end
end # of class methods
attr_reader :period
def initialize values
values ||= {}
#period = Period.new values[:period] || {}
super values
end
def period_attributes
#period
end
def period_attributes= new_values
#period.attributes = new_values
end
end
In the controller:
def search
#criteria = Criteria.new params[:criteria]
end
In the helper:
def criteria_index_path ct, options = {}
url_for :action => :search
end
In the view:
<%= form_for #criteria do |form| %>
<%= form.fields_for :period do |prf| %>
<%= prf.text_field :beginning_as_text %>
<%= prf.text_field :end_as_text %>
<% end %>
<%= form.submit "Search" %>
<% end %>
Produces the HTML:
<form action="/admin/search" id="new_criteria" method="post">
<input id="criteria_period_attributes_beginning_as_text" name="criteria[period_attributes][beginning_as_text]" type="text">
<input id="criteria_period_attributes_end_as_text" name="criteria[period_attributes][end_as_text]" type="text">
Note: The action attribute provided by the helper and the nested attributes naming format that makes it so simple for the controller to load all the values at once
There is the activerecord-tableless gem. It's a gem to create tableless ActiveRecord models, so it has support for validations, associations, types. It supports Active Record 2.3, 3.0, 3.2
The recommended way to do it in Rails 3.x (using ActiveModel) has no support for associations nor types.

Resources