Edit other user as admin, ruby on rails - html

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.

Related

Form fields autofilled on loading a signup page in Rails

I have this signup form code (the controller is added below) :
<%= form_with(model: #user, class: "shadow p-3 mb-3 bg-info rounded", local: true) do |f|%>
<div class="form-group row">
<%= f.label :username, class: "col-2 col-form-label text-light"%>
<div class="col-10">
<%= f.text_field :username, class: "form-control shadow rounded", placeholder: "Enter a username" %>
</div>
</div>
<div class="form-group row">
<%= f.label :email, class: "col-2 col-form-label text-light"%>
<div class="col-10">
<%= f.email_field :email, class: "form-control shadow rounded", placeholder: "Enter your e-mail address" %>
</div>
</div>
<div class="form-group row">
<%= f.label :password, class: "col-2 col-form-label text-light"%>
<div class="col-10">
<%= f.password_field :password, class: "form-control shadow rounded", placeholder: "Choose a password" %>
</div>
</div>
<div class="form-group row justify-content-center">
<%= f.submit class:"btn btn-outline-light btn-lg" %>
</div>
<% end %>
Even though I have placeholders set up (placeholder: "...."), when I load the page it becomes auto-filled with some personal values - e-mail + password.
The controller code for creating users is the following:
class UsersController <ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
before_action :require_user, only: [:edit, :update]
before_action :require_same_user, only: [:edit, :update, :destroy]
def show
#articles = #user.articles.paginate(page: params[:page], per_page: 2)
end
def index
#users = User.paginate(page: params[:page], per_page: 2)
end
def new
#user = User.new
end
def edit
end
def update
if #user.update(user_params)
flash[:notice] = "Your account information was successfully updated."
redirect_to #user
else
render 'edit'
end
end
def create
#user = User.new(user_params)
if #user.save
session[:user_id] = #user.id
flash[:notice] = "Welcome to the Alpha Blog #{#user.username}, you have successfully signed up."
redirect_to articles_path
else
render 'new'
end
end
def destroy
#user.destroy
session[:user_id] = nil if #user == current_user
flash[:notice] = "Account and all associaed articles successfully deleted."
redirect_to articles_path
end
private
def user_params
params.require(:user).permit(:username, :email, :password) #whitelisting
end
def set_user
#user = User.find(params[:id])
end
def require_same_user
if current_user != #user && !current_user.admin?
flash[:alert] = "You can only edit or delete your own profile"
redirect_to #user
end
end
end
Not sure how to disable that. Thanks!
form_with(model: #user, ... builds the form with whatever is in the #user variable.
Let's say you have a user like this:
$ #user = User.first
> #<User id: 1, email: "person#email.com", username: "Person", password_digest: [FILTERED]>
In this case, form_with fields will use the existing record values in the form.
If you've created a new user in the controller action for this view:
$ #user = User.new
> #<User id: nil, email: nil, username: nil, password_digest: nil>
then the form fields should be blank.
How to test if this is the issue:
Replace your #user with User.new:
<%= form_with(model: #user, ...
What else could be happening:*
The browser could be auto-filling form data, Chrome does this quite often.
A browser extension, like a password manager, could be auto-filling the form data

Hash password not saved in the password column

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 %>

Getting undefined method 'parent'

So i asked this question a while back before but i still cant seem to get this right . im trying to make my comment model make comments for both topics and posts. i just want Comments controller to be able to handle comments going to post or topic.
routes :
resources :topics, :posts do
resources :comments, only: [:create, :destroy]
end
Topic Model:
has_many :comments, dependent: :destroy
Comment Model:
belongs_to :post
belongs_to :topic
Post:
has_many :comments, dependent: :destroy
Comments Controller :
def create
if params[:post_id]
#parent = Post.find(params[:post_id])
#comment = #parent.comments.new(comment_params)
#comment.user = current_user
if #comment.save
flash[:notice] = "Comment saved successfully."
redirect_to [#parent.topic, #parent]
else
flash[:alert] = "Comment failed to save."
redirect_to [#parent.topic, #parent]
end
elsif params[:topic_id]
#parent = Topic.find(params[:topic_id])
#comment = #parent.comments.new(comment_params)
#comment.user = current_user
if #comment.save
flash[:notice] = "Comment saved successfully."
else
flash[:alert] = "Comment failed to save."
end
end
end
def comment_params
params.require(:comment).permit(:body)
end
comment/form.html
<%= form_for [#parent, #comment] do |f| %>
<div class="form-group">
<%= f.label :body, class: 'sr-only' %>
<%= f.text_field :body, class: 'form-control', placeholder: "Enter a new comment" %>
</div>
<%= f.submit "Submit Comment", class: 'btn btn-default pull-right' %>
<% end %>
I keep getting undefined local variable or method parent when trying to go to my topic/show view
also how can i implement comments to show up on topic/post view
undefined local variable or method parent
You need to change your local variables (parent & comment) to instance variables (#parent & #comment) in the controller action and as well in the view in order to use those in the view.
The below should work
<%= form_for [#parent, #comment] do |f| %>
<div class="form-group">
<%= f.label :body, class: 'sr-only' %>
<%= f.text_field :body, class: 'form-control', placeholder: "Enter a new comment" %>
</div>
<%= f.submit "Submit Comment", class: 'btn btn-default pull-right' %>
<% end %>
Also I've noticed that there are two #parent & #parant variables defined in the controller action. If its a typo then correct it.

Ruby on rails form data not not getting saved

So i am getting trouble in saving form data,.Any help will b appreciable
form is submitted without getting any error, but in database, nothing is stored
i am new on rails
users_controller
class UsersController < ApplicationController
def new
#user= User.new
end
def create
#user = User.new(params[:User])
if #user.save
flash[:notice]= "you signed up successfully"
flash[:color]= "valid"
else
flash[:notice]= "failed"
flash[:color]="invalid"
end
render "new"
end
end
new.html.erb
<% page_title="Signup" %>
<div class="Sign_Form">
<h1>Sign up</h1>
<%= form_for(:user, :url => {:controller => 'users', :action => 'create'}) do |f| %>
<p> Username:</br> <%= f.text_field :username %> </p>
<p> Email:</br> <%= f.text_field :email %> </p>
<p> Password:</br> <%= f.password_field :password %></p>
<p> Password Confirmation:</br> <%= f.password_field :password_confirmation %> </p>
<%= f.submit :Signup %>
<% end %>
<% if #user.errors.any? %>
<ul class="Signup_Errors">
<% for message_error in #user.errors.full_messages %>
<li>* <%= message_error %></li>
<% end %>
</ul>
<% end %>
</div>
in app/models/user.rb
class User < ActiveRecord::Base
attr_accessor :password
EMAIL_REGEX = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i
validates :username, :presence => true, :uniqueness => true, :length => { :in => 3..20 }
validates :email, :presence => true, :uniqueness => true #:format => EMAIL_REGEX
validates :password, :presence =>true #:confirmation => true #password_confirmation attr
validates_length_of :password, :in => 6..20, :on => :create
end
In users_controller, create method, you are using
#user = User.new(params[:User])
replace it with following code, hope it will work fine.
#user = User.new(params[:user])
And,also use strong params if you are using rails 4. Like follwoing.
def create
#user = User.new(user_params)
if #user.save
flash[:notice]= "you signed up successfully"
flash[:color]= "valid"
else
flash[:notice]= "failed"
flash[:color]="invalid"
end
render "new"
end
private
def user_params
params.require(:user).permit(:username, :account, :email, :password, :password_confirmation)
end
If, it still not works, then, please display your log.
If you are using Rails 4 you need to use strong parameters to whitelist the parameters you want to assign to your models.
This became non-optional in Rails 4 to prevent mass-assignment vulnerabilities where a malicious user can assign any property to a model after Egor Homakovs much publicised Github attack.
Also note that Ruby is case sensitive. This applies to hash keys as well:
irb(main):003:0> hash = { a: 1 }
=> {:a=>1}
irb(main):004:0> hash[:A]
=> nil
Which is why why you do User.new(params[:User]) you are actually doing User.new(nil)
This is a corrected version of your controller
class UsersController < ApplicationController
def new
#user= User.new
end
def create
#user = User.new(params[:User])
if #user.save
flash[:notice]= "you signed up successfully"
flash[:color]= "valid"
# You should redirect instead of rendering the form again
redirect_to #user # or redirect_to root_path
else
flash[:notice]= "failed"
flash[:color]="invalid"
render "new" # Needs to be inside the "else" statement
# Otherwise you will get a double render error
end
end
def user_params
params.require(:user)
.allow(:username, :email, :password, :password_confirmation)
end
end
Added:
You can also simplify your form_for to
<%= form_for(:user) do |f| %>
Rails will by convention route the form to UserController#create.
Also you should use <label> tags for accessibility, as they help people who use assistive technology such as screen readers to find the correct inputs.
By using the built in label helper rails will set up the for attribute and you can translate the label texts with Rails built in I18n functionality.
<% page_title="Signup" %>
<div class="Sign_Form">
<h1>Sign up</h1>
<%= form_for(:user) do |f| %>
<div class="row">
<%= f.label :username %>:</br>
<%= f.text_field :username %>
</div>
<div class="row">
<%= f.label :email %>:</br>
<%= f.text_field :email %>
</div>
<div class="row">
<%= f.label :password %>:</br>
<%= f.password_field :password %>
</div>
<%= f.submit :Signup %>
<% end %>
<% if #user.errors.any? %>
<ul class="Signup_Errors">
<%# for loops are almost never used in ruby. %>
<%# .each is the idiomatically correct way %>
<% #user.errors.full_messages.each do |message_error| %>
<li>* <%= message_error %></li>
<% end %>
</ul>
<% end %>
</div>

No route matches {:action=>"search", :controller=>"devise/index"}

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">
&nbsp
</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