How to display name of user who wrote comment to post (Rails) - ruby-on-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.

Related

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

how to show 'recently visited'?

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.

Can't mass-assign protected attributes:

Have tried the solutions for this common error in stackoverflow but none of them seem to work in this case, it might be that I already created an address field on the property before. I keep getting the mass assignment error.
Any help appreciated.
Address.rb
class Address < ActiveRecord::Base
attr_accessible :addressable_id, :addressable_type, :city, :county, :postcode, :street1, :street2
belongs_to :addressable, :polymorphic => true
end
Property.rb
class Property < ActiveRecord::Base
attr_accessible :name, :addresses_attributes
belongs_to :user
has_one :address, :as => :addressable
accepts_nested_attributes_for :address
validates :name, presence: true, length: { maximum: 200 }
validates :address, presence: true
validates :user_id, presence: true
end
Property Controller
class PropertiesController < ApplicationController
before_filter :authenticate_user!
before_filter :correct_user, only: :destroy
def index
#property= Property.all
end
def create
#property = current_user.properties.build(params[:property])
if #property.save
flash[:success] = " Property Added"
redirect_to root_path
else
render 'edit'
end
end
def new
#property = Property.new
#property.build_address
end
You should add
accepts_nested_attributes_for :address
and change
attr_accessible :name, :address_attributes
and if it doesn't work change both address to addressable

Stack level too deep: creating child-record

My problem: User has_one Profile. When new User is created, APP also automatically creates Profile, which belongs to User. I tried to do it through controller, through callback, always same error (Stack level too deep). My models:
class User < ActiveRecord::Base
has_secure_password
attr_accessible :email, :password, :password_confirmation
validates_uniqueness_of :email, :case_sensitive => false
validates :email, :email_format => true
validates :password, :length=> {:in=> 5...32}
validates :email, :password, :password_confirmation, :presence =>true
has_many :authentications
has_many :tests
has_many :answers
has_many :results
has_one :profile
#after_create :build_profile
#tried this way
def build_profile
self.build_profile
end
end
#
class Profile < ActiveRecord::Base
attr_accessible :user_id
belongs_to :user
end
#
def create
#user = User.new(params[:user])
#user.email=#user.email.downcase
if #user.save
session[:user_id] = #user.id
#profile=#user.build_profile
redirect_to root_url, notice: "Thank you for signing up!"
else
render "new"
end
end
Alsways same error. Why?
def build_profile
self.build_profile
end
This loops endlessly (and I can't see the point, what did you want to do?)
you should simply remove the build_profile method (don't worry, it's defined thanks to the association).
user = User.new
user.build_profile
|_ calls self.build_profile, but self is user
|_ calls user.build_profile
|_ ...

How to build the first User , with an invitation list model

I am trying to use invitations for my site . I want to know that ; My first User can't need an invitation ? How can I make an exception? I can guess that ,
I must use a rescue exception but I dont know where it must be done?
My users.rb model:
class User < ActiveRecord::Base
attr_accessible :nickname, :email, :password, :password_confirmation, :invitation_token
has_secure_password
has_many :friendships
has_many :friends, :through => :friendships
has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
has_many :inverse_friends, :through => :inverse_friendships, :source => :user
has_many :topics, dependent: :destroy
has_many :posts, dependent: :destroy
before_save { |user| user.email = email.downcase }
before_save { |user| user.nickname = nickname.downcase }
before_save :create_remember_token
validates :nickname, presence: true, length: { maximum: 150 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true,
format: { with: VALID_EMAIL_REGEX },
uniqueness: {case_sensitive: false }
validates :password, presence: true, length: { minimum: 6 }
validates :password_confirmation, presence: true
validates_presence_of :invitation_id, :message => 'gerekli'
validates_uniqueness_of :invitation_id
has_many :sent_invitations, :class_name => 'Invitation', :foreign_key => 'sender_id'
belongs_to :invitation
before_create :set_invitation_limit
def invitation_token
invitation.token if invitation
end
def invitation_token=(token)
self.invitation = Invitation.find_by_token(token)
end
private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
def set_invitation_limit
self.invitation_limit = 5
end
end
And this is the users_controller.rb:
def new
#user = User.new(:invitation_token => params[:invitation_token])
#user.email = #user.invitation.recipient_email if #user.invitation
end
def create
#user = User.new(params[:user])
if #user.save
sign_in #user
flash[:success] = "Giripedia'ya hoşgeldiniz'!"
redirect_to #user
else
render 'new'
end
end
Make a conditional validation. Let me give you a short example:
class User
# ...
validates_presence_of :invitation_id, :if => :invitation_needed?
# An invitation is needed if there is at least one user. If there
# are no users, there can't be an invitation.
def invitation_needed?
User.all.count >= 1
end
end
Details: See the manual on conditional validation
I m not sure if this is a good idea to write a conditional validation just to be able to save your first user.
You dont want to do a count query every time you are validating a user.
You can save your first user from console with skip validation option.
#user.save(:validate => false)

Resources