how to show 'recently visited'? - ruby-on-rails

I have created a web app that has user profiles, where users can search for fellow users based on interests, as well as post + attend events etc.. How might I add a feature where users can see who 'Recently visited' a certain event?
event.rb
class Event < ActiveRecord::Base
attr_accessible :title, :description, :location, :date, :time, :event_date
acts_as_commentable
has_many :comments, as: :commentable
belongs_to :user
has_many :event_participants, dependent: :destroy
has_many :participants, through: :event_participants, source: :user
end
user.rb
class User < ActiveRecord::Base
include PgSearch
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable,
:omniauth_providers => [:facebook, :twitter, :linkedin]
attr_accessible :email, :password, :password_confirmation, :zip, :gender, :remember_me, :first_name, :last_name,
:birthday, :current_password, :occupation, :address, :interests, :aboutme, :profile_image,
:photos_attributes, :age, :education, :ethnicity
has_many :authorizations, :dependent => :destroy
has_many :comments
has_many :events
has_many :photos, as: :attachable
has_many :questions
has_many :sent_messages, class_name: 'Message', foreign_key: :sender_id
has_many :received_messages, class_name: 'Message', foreign_key: :receiver_id
accepts_nested_attributes_for :photos
mount_uploader :profile_image, ProfileImageUploader
end
event_participants.rb
class EventParticipant < ActiveRecord::Base
attr_accessible :user_id, :event_id
belongs_to :user
belongs_to :event
validates :user_id, uniqueness: {scope: :event_id}
end
events_controller snippit
class EventsController < ApplicationController
before_filter :authenticate_user!
def index
#users = User.all
#user = current_user
#events = Event.all
#interesting_people = #users.order("random()").first(5)
end
def new
#event = Event.new
end
def create
#event = current_user.events.new(event_params)
respond_to do |format|
if #event.save
format.html { redirect_to :back, notice: 'Event was successfully created.' }
format.json { render action: 'show', status: :created, location: #event }
format.js
else
format.html { render action: 'new' }
format.json { render json: #event.errors, status: :unprocessable_entity }
format.js
end
end
end
def show
#users = User.all
#user = current_user
#event = Event.find(params[:id])
#commentable = #event
#comment = #event.comments.new
#interesting_people = #users.order("random()").first(5)
end

Based on your code, it looks like you could do something like:
#event.event_participants.include(:users).order('created_at desc').limit(X).map(&:user)
You could also try without the include:
#event.event_participants.order('created_at desc').limit(X).map(&:user)
But that will do N+1 queries. The join will perform better.
Where in the above code, X would be how many participants you want to show.

Related

undefined method `overall_avg' for #<Recipe::ActiveRecord_Relation:0x007f5154d4ea20>

After installing ratyrate and i've done like in Instruction at GItHub
I got this error
I need to add something at controller? or what?
I hope you will help me to solve this
I need to add something at controller? or what?
I hope you will help me to solve th
my model user.rb(using devise)
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
ratyrate_rater
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :recipe
end
my model recipe.rb
class Recipe < ApplicationRecord
belongs_to :user
has_many :ingredients
has_many :directions
has_many :comments, as: :commentable
ratyrate_rateable "recipe_rating"
accepts_nested_attributes_for :ingredients,
reject_if: proc { |attributes| attributes['name'].blank? },
allow_destroy: true
accepts_nested_attributes_for :directions,
reject_if: proc { |attributes| attributes['step'].blank? },
allow_destroy: true
validates :title, :description, :image, presence: true
has_attached_file :image, styles: { medium: "400x400#"}
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
end
my index.html.haml
- #recipe.each_slice(3) do |recipes|
.row
-recipes.each do |recipe|
.col-md-4
.recipe
.image_wrapper
= link_to recipe do
=image_tag recipe.image.url(:medium)
%h2= link_to recipe.title,recipe
.row
.small-2.large-2.columns
= imdb_style_rating_for #recipe, current_user
%br/
.small-2.large-4.columns
- if current_user
Recipe Ratings: #{rating_for #recipe, "recipe_rating"}
my ricipes_controller
class RecipesController < ApplicationController
before_action :find_recipe, only: [:show,:edit, :update, :destroy]
before_action :authenticate_user!, exept: [:index, :show]
def index
#recipe = Recipe.all.order("created_at DESC")
end
def show
end
def new
#recipe = current_user.recipe.build
end
def create
#recipe = current_user.recipe.build(recipe_params)
if #recipe.save
redirect_to #recipe, notice: "Successfully created new recipe"
else
render 'new'
end
end
def edit
end
def update
if #recipe.update(recipe_params)
redirect_to #recipe
else
render 'edit'
end
end
def destroy
#recipe.destroy
redirect_to root_path, notice: "Successfully deleted recipe"
end
private
def recipe_params
params.require(:recipe).permit(:title, :description, :image, ingredients_attributes: [:id, :name, :_destroy], directions_attributes: [:id, :step, :_destroy])
end
def find_recipe
#recipe = Recipe.find(params[:id])
end
end

Rails - Nested Strong parameters

I'm trying to create an user register using two models User and profile, nested strong parameters in one controller. when I send parameter I get this error unknown attribute 'profiles_attributes' for User. and I can't create user neither profile :
class User < ActiveRecord::Base
has_one :profile
has_many :apartments
has_many :session
has_secure_password
validates :email, presence: true, uniqueness: true
validates :password, presence: true
accepts_nested_attributes_for :profile
end
class Profile < ActiveRecord::Base
belongs_to :user
belongs_to :city
has_many :profile_universities
has_many :universities, through: :profile_universities
has_many :profile_preferences
has_many :preferences, through: :profile_preferences
has_one :photo, :as => :imageable
end
class Api::V1::UserController < ApplicationController
before_action :user_params
def create_without_facebook
#user= User.new(user_params)
if #user.save
#profile = Profile.new(user_params[:profiles_attributes])
render json: [#user, #profile]
else
render json: #user.errors, status: :unprocessable_entity
end
end
def user_params
params.require(:user).permit(:email, :password, profiles_attributes: [:first_name, :last_name, :birthday, :gender, :marital_status, :ocupation, :budget, :question, :about, :city])
end
end
use the singular profile_attributes if it's a has_one

Rails destroy action destroying the wrong record

I posted a similar question earlier and I thought that I had fixed this problem but I was wrong. I thought that the activity wasn't being deleted but turns out that it was deleting activity it was just the wrong one. I don't have this problem with any of my other models and this only happens on one of my apps. My forked app which has the exact same code works correctly. I don't know why this is happening.
projects_controller.rb
class ProjectsController < ApplicationController
before_filter :find_project, only: [:edit, :update, :destroy]
def create
params[:project][:about] = sanitize_redactor(params[:project][:about])
#project = current_member.projects.new(params[:project])
respond_to do |format|
if #project.save
current_member.create_activity(#project, 'created')
format.html { redirect_to #project }
format.json { render json: #project, status: :created, location: #project }
else
format.html { render action: "new" }
format.json { render json: #project.errors, alert: 'Please make sure all required fields are filled in and all fields are formatted correctly.' }
end
end
end
def destroy
#project = Project.find(params[:id])
#activity = Activity.find_by_targetable_id(params[:id])
if #activity
#activity.destroy
end
#project.destroy
respond_to do |format|
format.html { redirect_to profile_projects_path(current_member) }
format.json { head :no_content }
format.js
end
end
def find_project
#project = current_member.projects.find(params[:id])
end
end
member.rb
class Member < ActiveRecord::Base
def create_activity(item, action)
activity = activities.new
activity.targetable = item
activity.action = action
activity.save
activity
end
end
Migration
class CreateActivities < ActiveRecord::Migration
def change
create_table :activities do |t|
t.integer :member_id
t.string :action
t.integer :targetable_id
t.string :targetable_type
t.timestamps
end
add_index :activities, :member_id
add_index :activities, [:targetable_id, :targetable_type]
end
end
****EDIT****
activity.rb
class Activity < ActiveRecord::Base
belongs_to :member
belongs_to :targetable, polymorphic: true
acts_as_votable
self.per_page = 36
def self.for_member(member, options={})
options[:page] ||= 1
following_ids = member.following_members.map(&:id).push(member.id)
where("member_id in (?)", following_ids).
order("created_at desc").
page(options[:page])
end
end
project.rb
class Project < ActiveRecord::Base
belongs_to :member
attr_accessible :about, :blurb, :category, :markers, :video, :website, :name, :avatar, :banner, :marker_list, :city
acts_as_votable
acts_as_followable
acts_as_ordered_taggable
acts_as_ordered_taggable_on :markers
acts_as_messageable
has_many :comments, as: :commentable, :dependent => :destroy
has_many :uploads, as: :uploadable, :dependent => :destroy
has_many :updates, as: :updateable, :dependent => :destroy
def to_param
"#{id}-#{name.parameterize}"
end
end
member.rb
class Member < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :email_confirmation, :password, :password_confirmation, :remember_me,
:full_name, :user_name, :pursuits, :avatar, :bio, :city, :state, :country, :pursuit_list,
:facebook, :twitter, :linkedin, :soundcloud, :youtube, :vimeo, :instagram, :flickr, :google, :pinterest, :blog, :website, :banner
has_many :medium, :dependent => :destroy
has_many :projects, :dependent => :destroy
has_many :events, :dependent => :destroy
has_many :statuses, :dependent => :destroy
has_many :activities, :dependent => :destroy
has_many :listings, :dependent => :destroy
has_many :comments, :dependent => :destroy
has_many :uploads, :dependent => :destroy
has_many :updates, :dependent => :destroy
has_many :assets, :dependent => :destroy
acts_as_follower
acts_as_followable
acts_as_ordered_taggable
acts_as_ordered_taggable_on :pursuits
acts_as_voter
acts_as_messageable
def to_param
user_name
end
def name
user_name
end
def mailboxer_email(object)
return user_name
end
def create_activity(item, action)
activity = activities.new
activity.targetable = item
activity.action = action
activity.save
activity
end
end
Interesting...
--
Activity Model
You mention it's the Activity model which doesn't destroy correctly. With this in mind, you'll want to look at all the steps contributing to the destroy mechanism:
def destroy
...
#activity = Activity.find_by_targetable_id(params[:id])
#activity.destroy if #activity
First things first - what is targetable_id? Also, if you're using Rails 4, you'll be able to use the find_by method with a hash of attributes:
#activity = Activity.find_by targetable_id: params[:id]
This could be the main cause of the issue - the above code will basically look for any Activity records with the targetable_id attribute having the same id parameter as you passed from your request
I'm not a betting man, but I'd surmise this is where the issue lies
Polymorphic
Okay, I found the problem.
You're trying to call a polymorphic association without referencing it correctly. Polymorphic associations allow you to create an ActiveRecord association for multiple models, storing the associative data in a single table / model:
Notice how the above example (as your code) includes ______type column? This is VITAL to your solution - as it what stores the model you saved the ID for:
When you save data in ActiveRecord associations, it uses something called a foreign_key to define the associative data in your model. This foreign key is normally something like activity_id or similar, as you know already.
The difference is that your association is a polymorphic association, meaning you can store multiple model types in a single table. This means that ActiveRecord / Rails will have to refer to the model you're saving, which is where the _type column comes in
My theory is that your local database will have several models saved in your "polymorphic" datatable - meaning when you look for an ID, it's bringing back a record which isn't the correct model
Fix
I would recommend the following:
#app/models/project.rb
Class Project < ActiveRecord::Base
has_many :activities, as: :targetable, dependent: :destroy
end
#app/models/activity.rb
Class Activity < ActiveRecord::Base
belongs_to :targetable, polymorphic: true
end
I don't know your model associations, so I just made the above up. If you set up your associations as above, you'll be able to call the following:
#app/controllers/projects_controller.rb
Class ProjectController < ApplicationController
def destroy
#project = Project.find params[:id] # should find project.activities too
#project.destroy
end
end
I used the above for several important reasons:
You're using the same ID for both objects (means they're associated)
You can use the dependent: :destroy method
The bottom line is you will be able to destroy just the Project object, and have its dependants destroyed too, achieving your desired outcome

How to display name of user who wrote comment to post (Rails)

I'm creating a blog on Rails with posts, users(authentication with Devise), comments. If user will write comment to post I want to show his name above his comment. How can I do this? Please, help me
My comments controller:
class CommentsController < ApplicationController
def create
#post = Post.find(params[:post_id])
#comment = #post.comments.build(params[:comment])
#comment.save
redirect_to #post
end
def destroy
#comment = Comment.find(params[:id])
#comment.destroy
redirect_to #comment.post
end
end
My models:
class Comment < ActiveRecord::Base
attr_accessible :post_id, :text
belongs_to :post
belongs_to :user
end
class User < ActiveRecord::Base
has_many :posts, :dependent => :destroy
has_many :comments, :dependent => :destroy
validates :fullname, :presence => true, :uniqueness => true
validates :password, :presence => true
validates :email, :presence => true, :uniqueness => true
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :fullname
end
class Post < ActiveRecord::Base
attr_accessible :text, :title, :tag_list
acts_as_taggable
validates :user_id, :presence => true
validates :title, :presence => true
validates :text, :presence => true
belongs_to :user
has_many :comments
end
Just assign the user in comments_controller.rb
def create
#post = Post.find(params[:post_id])
#comment = #post.comments.build(params[:comment])
#comment.user = current_user
#comment.save
redirect_to #post
end
Next time spend a little more time researching your question, this is a common task and a very brief Google search would have saved you the trouble of asking.

Able to display all activity but unable to only show activity for followed users. Undefined methods

I followed Michael Hartl's Rails Tutorial to implement a follower system similar to Twitter's (railstutorial.org). For now, I want to use this follower system to only display activities of users followed by the user currently logged in. I'm able to display all activities in the system on the /activities page with no issue. The Activities controller code that works is as follows:
class ActivitiesController < ApplicationController
def index
#activities = PublicActivity::Activity.all
end
end
The index page for the Activities controller lists all of the posts made by all users. However, I want to edit the controller code to only display the activities of followed users. How can I do this? All my attempts lead to no method errors. Here are relevant items:
User model:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :first_name, :last_name, :title, :location, :aboutme, :works_attributes
# attr_accessible :title, :body
validates_presence_of :first_name, :last_name
validates_uniqueness_of :first_name, :last_name, :email, :case_sensitive => false
has_many :works, dependent: :destroy
accepts_nested_attributes_for :works
has_many :relationships, foreign_key: "follower_id", dependent: :destroy
has_many :followed_users, through: :relationships, source: :followed
has_many :reverse_relationships, foreign_key: "followed_id",
class_name: "Relationship",
dependent: :destroy
has_many :followers, through: :reverse_relationships, source: :follower
has_many :posts, dependent: :destroy
def full_name
[first_name, last_name].join(" ")
end
def following?(other_user)
relationships.find_by_followed_id(other_user.id)
end
def follow!(other_user)
relationships.create!(followed_id: other_user.id)
end
def unfollow!(other_user)
relationships.find_by_followed_id(other_user.id).destroy
end
end
Relationship model:
class Relationship < ActiveRecord::Base
attr_accessible :followed_id, :follower_id
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
validates :follower_id, presence: true
validates :followed_id, presence: true
end
User controller
class UsersController < ApplicationController
def index
#users = User.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #users }
end
end
def show
#user = User.find(params[:id])
#posts = #user.posts.all
#works = #user.works.all
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #user }
end
end
def following
#title = "Following"
#user = User.find(params[:id])
#users = #user.followed_users.all
render 'show_follow'
end
def followers
#title = "Followers"
#user = User.find(params[:id])
#users = #user.followers.all
render 'show_follow'
end
def posts
#user = User.find(params[:id])
#posts = #user.posts.all
render 'show_post'
end
end
Relationships controller
class RelationshipsController < ApplicationController
def create
#user = User.find(params[:relationship][:followed_id])
current_user.follow!(#user)
respond_to do |format|
format.html { redirect_to #user }
format.js
end
end
def destroy
#user = Relationship.find(params[:id]).followed
current_user.unfollow!(#user)
respond_to do |format|
format.html { redirect_to #user }
format.js
end
end
end
I've been stuck on this problem for way too long. Any help would be greatly appreciated. Please feel free to ask questions if you need more information.
How can I edit the Activities controller so that it displays activity for followed users?
**EDIT: It works!!
Disclaimer: I don't know anything about the public_activity gem, but here's what the documentation suggests you need to do:
Set the "owner" attribute on your activities.
Filter the activities you display: PublicActivity::Activity.where(owner_type: "User", owner_id: current_user.followed_users.map {|u| u.id}).all (This is based on this sample code.)

Resources