I’m starting with Ruby on Rails and get’m making an application that takes the likes of a facebook user and transforms them into products, creating a personalized gift list.
Well, I have three models: user, and like product. They are thus:
class Like < ActiveRecord::Base
belongs_to :user
has_one :product
attr_accessible :category, :created_time, :name
end
class Product < ActiveRecord::Base
belongs_to :user
has_one :like
attr_accessible :image_url, :price_max, :price_min, :product_name,
:url
end
class User < ActiveRecord::Base
has_many :likes, dependent: :destroy
has_many :products, through: :likes, dependent: :destroy
attr_accessible :email, :password, :password_confirmation, :remember_me,:first_name, :last_name, :gender, :facebook_username, :provider, :uid
end
I am also using two gems that help me catch the likes and turn them into products. I have two methods I use in ‘rails console’ for this:
#Facebook Client
client = FBGraph::Client.new(
client_id: 'client_id',
secret_id: 'secret_id',
token: 'token'
)
#Getting and Recording Likes
like = client.selection.me.likes.info!.data.data
like.sort_by{ |like| like.created_time.to_i }.reverse.each do |like|
case like.category
when 'Musician/band' then category = 'band'
...
else next
Like.create(category: category, created_time: like.created_time, name: like.name, user_id: current_user.id)
end
#Product API Client
buscape = Buscape.new(
app_id: 'app_id',
sandbox: true
)
#Getting product through likes, and recording
def find_for_products
likes.each do |like|
case like.category
when 'band' then
product = @buscape.products.where(keyword: URI.encode(like.name), categoryId: 2921, results: 1)['product']
...
else next
end
Product.create(
image_url:product['thumbnail']['url'],
price_max:product['priceMax'],
price_min:product['priceMin'],
product_name:product['productName'],
url:product['links']['link'][0]['url']
)
end
end
Using the rails console, I can manually register products and likes using Like.new and Product.new, and assign it to a user accessing and using ‘user.products’, but I have no idea how to implement it and in my view and in my comtroller to catch the likes of current_user and produce products at the moment the user clicks a button ‘Find products for me’
Can anyone help me?
If you’re using resources, you can define a new action on
Userin yourroutes.rbfile, like this:Then implement this action in the controller class.
One option is to put the code you have for querying FB and finding products into a
selfmethod in theProductmodel, something likeProduct.find_and_create_products(user). Or alternatively into a separate module in a new file inlibdirectory in your rails app. Then call it from the controller.If this operation takes a long time, you can later add some additonal code to run it as a delayed job, with something like delayed_job.