I'm having a problem with my research routes. they accuse this error:
ActionController::UrlGenerationError in Devise::Sessions#new
No route matches {:action=>"search", :controller=>"devise/index"}
my application:
<!DOCTYPE html>
<html>
<head>
<title>Javendi</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<div class = 'search', style="display:none">
<%= form_for root_path, :url => {:action => 'search', :controller=>"index"} do |f|%>
<%= text_field_tag "ad[price_min]", #ads_min, :placeholder => 'Price min', class: 'price' %>
<%= text_field_tag "ad[price_max]", #ads_max, :placeholder => 'Price max', class: 'price' %><br>
<%= text_field_tag "ad[title]", #ads_text, :placeholder => 'Ad name', class: 'titlesearch' %><br>
<div class='categorysearch'>
<%= collection_select :ad, :category_id, Category.all,:id,:name,:prompt => true, :selected => #ads_category_id %>
<br></div>
<%= f.submit'Searc', class: 'bottomsearch' %>
<%end%>
</div>
<div class="cima">
<!-- <img src="assets/2.gif" border="0" onmouseover="this.src='assets/7.gif'" onmouseout="this.src='assets/2.gif'"> -->
<div class= 'logout'>
<% if user_signed_in? %>
<%= link_to image_tag('exit.png', width: '50px', height:'50px'),destroy_user_session_path, method: :delete %>
<%else%>
<%end%>
</div>
<div class= "home">
<%= link_to image_tag('logo.png'),root_path %>
</div>
<div class="javendi">
<% if user_signed_in? %>
<button class= 'botton1'>
<%= link_to 'Editar Perfil', edit_user_registration_path %>|
<%= link_to 'Novo Anúncio', new_ad_path %>|
<%= link_to 'Meus Anúncios', my_ads_path %>|
<%= link_to 'Meus Favoritos', fav_ads_path %>
</button>
<%else%>
<button class= 'botton'>
<%= link_to 'Cadastre-se', new_user_registration_path %> |
<%= link_to 'Login', new_user_session_path %>
</button>
<%end%>
<div class='triangule'>
<div class="seta-cima">
</div>
</div>
</div>
<% if user_signed_in? %>
<div id='iconsearh2'>
<%= image_tag("search.png") %>
</div>
<%else%>
<div id='iconsearh'>
<%= image_tag("search.png") %>
</div>
<%end%>
</div>
<script type="text/javascript">
$('#iconsearh').click(function(){
if($('.search').is(':visible')){
$('.search').slideUp('fast')
$('.seta-cima').css("display","none");
}else{
$('.search').slideDown('fast')
$('.seta-cima').show();
}
});
</script>
<script type="text/javascript">
$('#iconsearh2').click(function(){
if($('.search').is(':visible')){
$('.search').slideUp('fast')
$('.seta-cima').css("display","none");
}else{
$('.search').slideDown('fast')
$('.seta-cima').show();
}
});
</script>
<div class='cima2'>
<div class='welcome'>
<% if current_user.present?%>
welcome <%=current_user.name%>
<%end%>
</div>
<div class= 'createad'>
<%= image_tag('7.gif', width: '50px', height:'50px')%>
</div>
</div>
<div class="results">
<%= yield %>
</div>
<div class= "bot">
 
</div>
</div>
</body>
</html>
my ads model:
class Ad < ActiveRecord::Base
validates_presence_of :title, message: "deve ser preenchido"
validates_presence_of :price, message: "deve ser preenchido"
validates_presence_of :adress, message: "deve ser preenchido"
validates_presence_of :email, message: "deve ser preenchido"
validates_presence_of :phone, message: "deve ser preenchido"
belongs_to :user
belongs_to :category
has_many :photos, :dependent => :destroy
accepts_nested_attributes_for :photos, :allow_destroy => true
has_many :user_ad_favs
def can_edit?(current_user)
if current_user.present?
return current_user.id == self.user_id
end
end
def self.search(query)
category = query[:category_id].present? ? "category_id = #{query[:category_id]}" : nil
title = query[:title].present? ? "title LIKE '%#{query[:title]}%'" : nil
price_min = query[:price_min].present? ? "price >= #{query[:price_min].to_f}" : nil
price_max = query[:price_max].present? ? "price <= #{query[:price_max].to_f}" : nil
query = [category, title, price_min, price_max].compact.join(" AND ")
return Ad.where ( query )
end
def user_fav(user)
return self.user_ad_favs.find_by_user_id_and_ad_id(user.id, self.id)
end
end
my ads controller:
class AdsController < ApplicationController
before_action :set_ad, only: [:show, :edit, :update, :destroy, :fav_ad,:unfav_ad, :search,]
# GET /ads
# GET /ads.json
def index
#ads = Ad.all
end
# GET /ads/1
# GET /ads/1.json
def show
end
# GET /ads/new
def new
#ad = current_user.ads.build
1.times { #ad.photos.build}
end
# GET /ads/1/edit
def edit
end
def search
#ads_min = params[:ad][:price_min]
#ads_max = params[:ad][:price_max]
#ads_title = params[:ad][:title]
#ads_category_id = params[:ad][:category_id]
#ads = Ad.search(params[:ad])
render :action => 'index'
end
# POST /ads
# POST /ads.json
def create
#ad = current_user.ads.build(ad_params)
respond_to do |format|
if #ad.save
format.html { redirect_to #ad, notice: 'Ad was successfully created.' }
format.json { render :show, status: :created, location: #ad }
else
format.html { render :new }
format.json { render json: #ad.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /ads/1
# PATCH/PUT /ads/1.json
def update
respond_to do |format|
if #ad.update(ad_params)
format.html { redirect_to #ad, notice: 'Ad was successfully updated.' }
format.json { render :show, status: :ok, location: #ad }
else
format.html { render :edit }
format.json { render json: #ad.errors, status: :unprocessable_entity }
end
end
end
# DELETE /ads/1
# DELETE /ads/1.json
def destroy
#ad.destroy
respond_to do |format|
format.html { redirect_to ads_url, notice: 'Ad was successfully destroyed.' }
format.json { head :no_content }
end
end
def fav_ad
user_ad_fav = #ad.user_fav(current_user)
if user_ad_fav.present?
user_ad_fav.update_attribute(:fav, true)
else
#ad.user_ad_favs.create(:user_id => current_user.id,:ad_id => #ad.id,:fav => true)
end
respond_to do |format|
format.js {render inline: "location.reload();"}
end
end
def unfav_ad
#ad.user_fav(current_user).update_attribute(:fav, false) if #ad.user_fav(current_user).present?
respond_to do |format|
format.js {render inline: "location.reload();"}
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_ad
#ad = Ad.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def ad_params
params.require(:ad).permit(:title, :price, :adress, :city, :state, :description, :email, :phone, :phone_type, :category_id, :photos_attributes =>[:photo])
end
end
You made a mistake in the :controller parameter in your form_for:
<%= form_for root_path, :url => {:action => 'search', :controller=>"index"} do |f|%>
First of all, the :controller should be 'ads' since the search action is in the AdsController you provided a sample of.
Second, you're using form_for wrong. You're passing in two different paths, root_path and the :url hash. The first parameter should be the model you're trying to make a form for. But you don't need that here, you just want a search form, so use form_tag instead:
<%= form_tag :action => 'search', :controller=>"ads" do %>
http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-form_tag
Related
I have this MVC project of a time clock, and I want to do the following configuration on it: that the user just click on a button and register the "clock_in" and click on another button and register the "clock_out" below are the controller, the view and the model.If anyone can help me I will be very grateful
shifts_controller.rb
def create
#shift = Shift.new(shift_params.merge(user: current_user)) # quando criar ja mostra o id
respond_to do |format|
if #shift.save
format.html { redirect_to action: 'show', user_id: current_user, id: #shift, notice: 'Shift was successfully created.' }
format.json { render :show, status: :created, location: #shift }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #shift.errors, status: :unprocessable_entity }
end
end
end
shift.rb
class Shift < ApplicationRecord
attr_accessor :clock_in, :clock_out, :user_id
belongs_to :user
def push_in
self.clock_in = DateTime.now - 3.hours
end
def push_out
self.clock_out = DateTime.now - 3.hours
end
end
_form.html.erb
<%= simple_form_for(#shift, url: url, method: method )do |f| %>
<%= f.error_notification %>
<%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>
<div class="form-inputs">
<%= f.time_field :push_in, value: f.object.push_in.strftime("%H:%M") %>
<%= f.date_field :push_in %>
</div>
<div class="form-inputs">
<%= f.time_field :push_out, value: f.object.push_in.strftime("%H:%M") %>
<%= f.date_field :push_out %>
</div>
<div class="form-actions">
<br/><%= f.button :submit %>
</div>
<% end %>
I want, that a user with the admin role can edit other users from users/index.html.erb view. I'm not the first one asking this question, but all the given answers lack clear instructions.
So the problem is; after editing the fields, when I click on the 'Updtate' button in users/index.html.erb view, the page is reloaded but no changes appens.
Aditionnal infos: I'm using Devise and Omniauth facebook.
The users are display in the users/index via a partial:
<td>
<div class="field">
<%= f.text_field :name, class: 'form-control' %>
</div>
</td>
<td>
<div class="field">
<%= f.text_field :email, class: 'form-control' %>
</div>
</td>
<td>
<div class="actions">
<%= f.submit I18n.translate('control.update'), class: 'btn sign-up-button' %>
</div>
</td>
<td>
<!-- display a delete button if the user is not the current_user -->
<%= link_to(I18n.translate('control.delete'), user_path(user), :data => { :confirm => "Are you sure?" }, :method => :delete, :class => 'btn') unless user == current_user %>
</td>
users/index.html.erb:
<div class="container">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<h2 class="text-center"><%= I18n.translate('user.users_list') %></h2>
<div class="column">
<table class="table">
<tbody>
<% #users.each do |user| %>
<tr>
<%= render user %>
</tr>
<% end %>
</tbody>
</table>
</div>
<ul class=”pagination”>
<li><%= will_paginate(#users) %></li>
</ul>
</div>
</div>
</div>
My user_controller.rb
class UsersController < ApplicationController
before_action :ensure_admin, :except => :show
def index
#users = User.paginate(:page => params[:page], :per_page => 8)
end
def show
#user = User.find_by_name(params[:id])
end
def edit
#user = User.find(params[:id])
end
def update
#user = User.find(params[:id])
if #user.update(secure_params)
redirect_to users_path, :notice => "User updated."
else
redirect_to users_path, :alert => "Unable to update user."
end
end
def destroy
user = User.find(params[:id])
user.destroy
redirect_to users_path, :notice => "User deleted."
end
private
def ensure_admin
if(current_user.role == 'admin')
return
end
redirect_to root_path, :alert => "Access denied."
end
def secure_params
params.require(:user).permit(:role)
end
def user_params
params.require(:user).permit(:email, :name, :password)
end
end
My routes:
Rails.application.routes.draw do
root to: 'pages#index'
get 'users/index'
# you can type '/users' to view the users
match '/users', to: 'users#index', via: 'get'
devise_for :users, :controllers => { :registrations => "registrations",
:path_prefix => 'd',
:omniauth_callbacks => "users/omniauth_callbacks" }
resources :users
scope '/:locale' do
devise_scope :user do
get 'login', to: 'devise/sessions#new'
end
devise_scope :user do
get 'signup', to: 'devise/registrations#new'
end
end
Here in the user_controller update action you are calling secure_params def, which is permitting only "role" field.
I think you should to use user_params in update action like below
def update
#user = User.find(params[:id])
if #user.update(user_params)
redirect_to users_path, :notice => "User updated."
else
redirect_to users_path, :alert => "Unable to update user."
end
end
Or you will have to permit other params also in secure_params def like
def secure_params
params.require(:user).permit(:role,:name,:email)
end
Hope it would help you.
I have a nested form that i use to create new records in the database. However, the edit functionality doesn't update those records once edited. I seem to have everything set up correctly, as i didn't find any abnormalities when comparing it to code i found on the internet or scaffolded code. What am i doing wrong?
This is part of enquiries_controller:
def edit
#nog op kunnen slaan!!!! 1-01-17 Marco
#enquiry = Enquiry.find(params[:id])
#enquiry.enquirymeasures.build
#enquiry.tools.build
#enquiry.build_applicant
#enquiry.signatures.build
#enquiry.gasmeters.build
end
# POST /enquiries
# POST /enquiries.json
def create
#enquiry.user_id = current_user.id
#enquiry = Enquiry.new(enquiry_params)
##enquiry.enquirymeasures.build
respond_to do |format|
if #enquiry.save
format.html { redirect_to #enquiry, notice: 'Enquiry was successfully created.' }
format.json { render :show, status: :created, location: #enquiry }
else
format.html { render :new }
format.json { render json: #enquiry.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /enquiries/1
# PATCH/PUT /enquiries/1.json
def update
respond_to do |format|
if #enquiry.update(enquiry_params)
format.html { redirect_to #enquiry, notice: 'Enquiry was successfully updated.' }
format.json { render :show, status: :ok, location: #enquiry }
else
format.html { render :edit }
format.json { render json: #enquiry.errors, status: :unprocessable_entity }
end
end
end
THe enquiry model
class Enquiry < ActiveRecord::Base
has_many :enquirymeasures, dependent: :destroy
accepts_nested_attributes_for :enquirymeasures, :reject_if => lambda { |a| a[:responsible].blank? }, :allow_destroy => true
has_many :tools, dependent: :destroy
accepts_nested_attributes_for :tools
has_many :controls, dependent: :destroy
accepts_nested_attributes_for :controls
has_one :applicant, dependent: :destroy
accepts_nested_attributes_for :applicant
has_one :contractor, through: :applicant
has_many :signatures, dependent: :destroy
accepts_nested_attributes_for :signatures
has_many :representatives , through: :signatures, :source => :representatives
has_many :gasmeters, dependent: :destroy
accepts_nested_attributes_for :gasmeters
belongs_to :user
end
and part of the _form partial(over 200 lines in total):
<%= form_for(#enquiry) do |f| %>
<form role="form">
<% if #enquiry.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#enquiry.errors.count, "error") %> prohibited this enquiry from being saved:</h2>
<ul>
<% #enquiry.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<h1 align="center">Vul de onderstaande velden in om een werkvergunning aan te vragen.</h1>
<p align="center">Algemene informatie</p>
..........
<p align="center">De laatste stap bestaat uit het ondertekenen van het formulier met uw handtekening.</p>
<div class="form-group">
<%= f.fields_for :signatures do |s| %>
<%= f.fields_for :representatives do |sr| %>
<%= s.label :Gemachtigde %><br>
<%= s.collection_select(:representative_id, Representative.all, :id, :name, prompt: true) %>
<br>
<%= s.label :datum %><br>
<%= s.datetime_select :date %>
<br>
<%= s.label :Handtekening %><br>
<%= s.text_field :signature %>
<%# 17-1-2017 baseren van 1 dropdown op de andere %>
<% end %>
<% end %>
</div>
<div class="form-group">
<p> Goedkeuring van het formulier door JPB Groep</p>
<% if can? :manage, Enquiry %>
<%= f.label :Goedgekeurd %>
<%= f.check_box :approved %>
<%end%>
</div>
<div class="actions">
<%= f.submit %>
</div>
</form>
<% end %>
After some fiddling, i did manage to get the data entered in the record visible when editing a record, but saving doesnt work. I can see that the console uses push, but it doesn't fire a update query.
I get no error so the page just goes back to the index page when hitting submit.
Added route
Rails.application.routes.draw do
devise_for :users
scope "/Admin" do
resources :users, :enquiries, :roles
end
scope "/Aanvrager" do
resources :users, :enquiries
end
mount RailsAdmin::Engine => '/admin', :as => 'rails_admin'
root 'enquiries#index'
get 'welcome/Index'
enquiry_params
def enquiry_params
params.require(:enquiry).permit(:id, :reference, :location, :description, :date, :amount, :approved, enquirymeasures_attributes: [:id, :responsible, :done, :needed, :measurement_id, :user],
tools_attributes: [:id, :handtool, :other, :motorvehicle, :compressor, :ramp, :scaffold, :crane, :ladder, :generator, :tankladder],
applicant_attributes: [:id, :name, :email, :contractor_id],
signatures_attributes: [:id, :date, :signature, :representative_id],
gasmeters_attributes: [:id, :date, :tester, :signature, :oxigen, :o_needed, :o_continu, :explosives, :e_needed, :e_continu, :mat1, :mat1_needed, :mat1_continu, :mat2, :mat2_needed, :mat2_continu, :mat3, :mat3_needed, :mat3_continu]).merge(user_id: current_user.id)
end
I am trying to store hash password in my users table while registration. Please see my code:
users_controller.rb
def login
#title = 'Login'
#render layout: 'login'
end
def create_login
user = User.authenticate(params[:user][:username], params[:user][:password])
if user
log_in user
redirect_to '/admin'
else
flash[:danger] = 'Invalid email/password combination' # Not quite right!
redirect_to :back
end
end
def register
#user = User.new
#title = 'Register'
end
def create_register
params[:user][:uniq_id] = generate_uniq
#user = User.new(create_user_params)
#raise #user.inspect
respond_to do |format|
if #user.save
format.html { redirect_to :success, success: 'Registration was successfully created.' }
format.json { redirect_to :register, status: :created, location: #users }
else
format.html { render :register }
format.json { render json: #users.errors, status: :unprocessable_entity }
end
end
end
private
def create_user_params
params.require(:user).permit(:uniq_id, :name, :username, :email, :password, :password_confirmation, :password_salt, :dob, :address)
end
register.html.erb
<%= form_tag("/register", method: "post") do %>
<%#= form_tag(#user) do |f| %>
<% if #user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#user.errors.count, "error") %> prohibited this user from being saved:</h2>
<ul>
<% #user.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= text_field :user, :name, placeholder:'NAME', required: true %>
<div style="position: relative;">
<span id="chk-username" style="position: absolute;font-size: 12px;right: 2%; bottom: 5%; z-index: 9; display: block;"></span>
<%= text_field :user, :username, placeholder:'USERNAME', 'data-validate':"/users/check_username", required: true %>
</div>
<div style="position: relative;">
<span id="chk-email" style="position: absolute;font-size: 12px;right: 2%; bottom: 5%; z-index: 9; display: block;"></span>
<%= text_field :user, :email, placeholder:'EMAIL', 'data-validate':"/users/check_email", required: true %>
</div>
<%= password_field :user, :password, placeholder:'PASSWORD', required: true %>
<%= password_field :user, :password_confirmation, placeholder:'CONFIRM PASSWORD', required: true %>
<div class="submit">
<input type="submit" value="REGISTER" >
<input type="button" onclick="location.href = '<%= request.base_url %>/login'" value="LOGIN" >
</div>
<p>Forgot Password ?</p>
<% end %>
user.rb
class User < ActiveRecord::Base
#has_secure_password
attr_accessor :password
before_save :encrypt_password
validates :name, presence: true
validates :name, length: { minumum:2, maximum: 30 }
validates :password, :presence =>true,
:length => { :minimum => 6, :maximum => 40 },
:confirmation =>true
validates :username, :presence => true,
:uniqueness => { :case_sensitive => false }
email_regex = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => { :case_sensitive => false }
def self.authenticate(input_username, input_password)
user = find_by_username(input_username)
if user && user.password == BCrypt::Engine.hash_secret(input_password, user.password_salt)
user
else
nil
end
end
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password = BCrypt::Engine.hash_secret(password, password_salt)
end
end
end
routes.rb
get 'register' => 'users#register'
post 'register' => 'users#create_register'
Here is my database table.
users.sql (customize table)
+----+----------+------------+-----------+----------------+
| id | name | username | password | password_salt |
+----+----------+------------+-----------+----------------+
| 1 | chinmay | chinu | NULL |$2a$10$15fWDt.. |
| 2 | sanjib | sanjib | NULL |$2a$10$85DyMr.. |
+----+----------+------------+-----------+----------------+
I get NULL value in my password column. Please help me and let me know where the error is in my code.
Your main error is that your are using attr_accessor :password to create a getter/setter for the password attribute that overrides the getter and setter that ActiveRecord creates from the database schema.
However your whole approach to password encryption is flawed - you should have password as a purely virtual attribute and name your database column password_digest or encrypted_password.
Unless its for pure learning purposes should use the has_secure_password macro that Rails provides instead of reinventing the password encryption wheel and getting hacked.
1. Add a password_digest column to user:
rails g migration AddPassWordDigestToUser password_digest:string:index
You might want to remove the password_salt column as well as it is not used by ActiveModel::SecurePassword.
class AddPassWordDigestToUser < ActiveRecord::Migration
def change
add_column :users, :password_digest, :string
add_index :users, :password_digest
remove_column :users, :password_salt
remove_column :users, :password
end
end
2. Add has_secure_password to the User model:
class User < ActiveRecord::Base
has_secure_password
end
3. RESTful routes
You may want to correct your routes so they are resource oriented and not action oriented and follow the rails conventions:
GET /registrations/new registations#new - sign up form
POST /registrations registations#create - create user
GET /sessions/new sessions#new - sign in form
POST /sessions sessions#create - sign in user
You can setup the routes with just:
resources :registrations, only: [:new, :create]
resources :sessions, only: [:new, :create]
See Rails Routing from the Outside In.
4. Binding forms and controllers.
You are setting up the controller properly however your form is not bound to the #user model instance you are creating in your controller.
This means that the values the user enters disappear after a unsuccessful form submission.
Also pay attention to the pluralization and naming of your variables! You are inconsistently using #user and #users. In this case #users will always be nil and cause an error.
app/controllers/registrations_controller.rb:
class RegistationsController < ApplicationController
def new
#user = User.new
end
def create
# Use a block instead of messing with the incoming params.
#user = User.new(user_params) do |u|
u.uniq_id = generate_uniq
end
if #user.save
respond_to do |format|
format.html { redirect_to root_path, success: "Welcome #{#user.email}" }
format.json { status: :created, location: #user }
end
else
respond_to do |format|
format.html { redirect_to :new }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation)
end
end
app/views/registrations/new.html.erb:
<%= form_for(#user, url: registrations_path) do |f| %>
<div class="row">
<%= f.label :email %>
<%= f.text_field :email %>
</div>
<div class="row">
<%= f.label :password %>
<%= f.password_field :password %>
</div>
<div class="row">
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation %>
</div>
<% end %>
In my rails application, I am using the gem, socialization.
I just can't figure out how to display the amount of likes!
My post controller :
class PostsController < ApplicationController
# GET /posts
# GET /posts.json
def index
#posts = Post.all(:order => "created_at DESC")
#posts_not_signed_in = Post.all(:order => "created_at DESC")
#post = Post.new
#users = User.all(:order => "created_at DESC")
respond_to do |format|
format.html # index.html.erb
format.json { render json: #posts }
end
end
def like
post.liked_by current_user
redirect_to root_path
end
# GET /posts/1
# GET /posts/1.json
def show
redirect_to posts_path
end
# GET /posts/new
# GET /posts/new.json
def new
#post = Post.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #post }
end
end
# GET /posts/1/edit
def edit
#post = Post.find(params[:id])
end
# POST /posts
# POST /posts.json
def create
#post = current_user.posts.build(params[:post])
respond_to do |format|
if #post.save
format.html { redirect_to #post, notice: 'Post was successfully created.' }
format.json { render json: #post, status: :created, location: #post }
else
format.html { render action: "new" }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
# PUT /posts/1
# PUT /posts/1.json
def update
#post = Post.find(params[:id])
respond_to do |format|
if #post.update_attributes(params[:post])
format.html { redirect_to #post, notice: 'Post was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
# DELETE /posts/1
# DELETE /posts/1.json
def destroy
#post = Post.find(params[:id])
#post.destroy
respond_to do |format|
format.html { redirect_to posts_url }
format.json { head :no_content }
end
end
end
My 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])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #user }
end
end
def follow
#user = User.find(params[:id])
current_user.toggle_follow!(params[:id])
redirect_to root_path
end
def unfollow
#user = User.find(params[:id])
current_user.stop_following(#user)
redirect_to root_path
end
end
My post model :
class Post < ActiveRecord::Base
attr_accessible :status, :author, :username, :id, :user_id, :user, :website, :bio, :skype, :dob, :age, :email, :motto, :follower, :followable, :votes
belongs_to :user
has_many :like
has_many :likes
validates :status, :presence => true
acts_as_likeable
acts_as_votable
end
My 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, :username, :user_id, :id, :website, :bio, :skype, :dob, :age, :motto, :follower, :followable
has_many :posts
acts_as_liker
# attr_accessible :title, :body
end
My view :
<% if user_signed_in? %>
<h1 id="welcome" class="nuvo">Welcome <%= current_user.username %>!</h1>
<% else %>
<h1 id="welcome" class="nuvo">Log-In to make some posts!</h1>
<% end%>
<div class="follow-row">
<div class="titan-users nuvo"><h2>BoomIt Users</h2></div>
<div class="user-row nuvo"><%= link_to 'coreypizzle', user_path(1) %> - <%= link_to 'BoomBoard', dashboard_path(1) %></div>
<% #users.each do |user| %>
<div class="user-row nuvo"><%= link_to user.username, user_path(user.id) %> - <%= link_to 'BoomBoard', dashboard_path(user.id) %></div>
<% end %>
</div>
<div class="statuses">
<% if user_signed_in? %><div class="status-form"><%= render 'form' %></div><% end %>
<% if user_signed_in? %>
<% #posts.each do |post| %>
<div class="post">
<div class="tstamp">
<%= image_tag avatar_url_small(post.user), :class => 'gravatar' %>
<strong>Posted <%= time_ago_in_words(post.created_at) %> ago by <%= post.user.username %></strong>
</div>
<div class="status"><%= post.status %></div>
<div class="likearea"><%= link_to 'BoomThis', 'posts/like', :class => 'wtxt nuvo' %> - <%= #post.likes.size %></div>
</div>
<% end %>
<% else %>
<% #posts_not_signed_in.each do |post| %>
<div class="post">
<div class="tstamp">
<%= image_tag avatar_url_small(post.user), :class => 'gravatar' %>
<strong>Posted <%= time_ago_in_words(post.created_at) %> ago by <%= post.user.username %></strong>
</div>
<div class="status"><%= post.status %></div>
</div>
<% end %>
<% end %>
</div>
Any help would be greatly appreciated!
First
has_many :like
has_many :likes
I think you mean just
has_many :likes
So you would do
#likes_num = #post.likes.count
Which will create a query for the number of likes, and not the actually likes themselves.
Old question, but i couldn't find this either.
The correct method call appears to be:
post.likers(User).count
I'm still unsure why you have to pass the model name in, perhaps so you can ask for the number of likes from that class of liker?
This works though.