Reputation: 25036
I'm trying to call a method when a button is clicked to go and fetch a tweet using the Twitter gem, and store that in my database.
I have a model called Sponsor (which includes a column storing a twitter user name), and a model called Sponsortweet:
models/sponsor.rb:
class Sponsor < ActiveRecord::Base
attr_accessible :facebook, :name, :twitter
has_many :sponsortweets, dependent: :destroy
validates :name, presence: true, uniqueness: { case_sensitive: false }
VALID_TWITTER_REGEX = /\A^([a-zA-Z](_?[a-zA-Z0-9]+)*_?|_([a-zA-Z0-9]+_?)*)$/
validates :twitter, format: { with: VALID_TWITTER_REGEX },
uniqueness: { case_sensitive: false }
def create_tweet
tweet = Twitter.user_timeline(self.twitter).first
self.sponsortweets.create!(content: tweet.text,
tweet_id: tweet.id,
tweet_created_at: tweet.created_at,
profile_image_url: tweet.user.profile_image_url,
from_user: tweet.from_user,)
end
end
models/sponsortweet.rb:
class Sponsortweet < ActiveRecord::Base
attr_accessible :content, :from_user, :profile_image_url, :tweet_created_at, :tweet_id
belongs_to :sponsor
validates :content, presence: true
validates :sponsor_id, presence: true
default_scope order: 'sponsortweets.created_at DESC'
end
In controllers/sponsors_controller.rb:
def tweet
@sponsor = Sponsor.find_by_id(params[:id])
@sponsor.create_tweet
end
Relevant line in my routes.rb:
match 'tweet', to: 'sponsors#tweet', via: :post
In my view (views/sponsors/show.html.haml):
= button_to :tweet, tweet_path
With this code, I get the following error when clicking on the button:
undefined method
create_tweet' for nil:NilClass`
If I change to use find (instead of find_by_id), the error is:
Couldn't find Sponsor without an ID
...which makes me think that an ID isn't being passed, since as far as I know, using find raises an error, whereas find_by_id returns nil.
What should I change to cause an ID to be passed?
Upvotes: 2
Views: 2674
Reputation: 107728
You need to pass through the id
parameter with the path helper:
= button_to :tweet, tweet_path(:id => @sponsor.id)
If you don't want it in the query string:
= form_tag tweet_path do |f|
= hidden_field_tag :id => @sponsor.id
= submit_tag "Tweet"
This does the same thing as your button_to
, but adds a hidden field to the form that is generated.
Upvotes: 2