I'm trying to get a user from his profile (user_path) can register his vehicles (new_user_car_path). but i got this error:
Routing Error
No route matches {:action=>"new", :controller=>"cars"}
for that i have the next routes.rb
Estaciones::Application.routes.draw do
root :to => "static_pages#home"
match '/contact', :to=>'static_pages#contact'
match '/about', :to=>'static_pages#about'
devise_for :users
resources :users do
resources :cars, :only => [:new, :create, :edit, :destroy]
end
here is part of the user_path
<div class="container">
<fieldset>
<h1><%= #user.email %></h1>
<br>
<h2>options</h2>
<p>
<strong>new car registration</strong>
<%= link_to "Sign up now!", new_user_car_path, :class => "btn btn-primary" %>
</p>
<p>
<strong>all cars view</strong>
</p>
</fieldset>
</div> <!-- /container -->
and my CarsController
class CarsController < ApplicationController
def new
#car = Car.new
end
def create
#car = current_user.cars.build(params[:car])
if #car.save
redirect_to current_user, :flash => { :success => "car created!" }
else
redirect_to new_user_car_path, :flash => { :success => "sorry try again" }
end
end
end
you need to pass information to route, so that it can determine where to go.
if you want to create a new car for a user, you need to pass the user. otherwise rails will not know where to get the user from... which is kind of logical if you think about it for more then a second...
new_user_car_path(user)
Related
I have created a ToDoList based off Hartl's tutorial, and following a video and worded tutorial to add a tagging system. I have followed till Section 10, where they asked me to modify my new.html.erb file to the code as shown on the source. To improvise for structural differences in code, I would edit some other files, like in this case, my micropost_form partial instead. Occasionally, I alternated between the code in the video and code in the worded tutorial because some of them would produce error messages or would not produce the required functionality. Here are the files that I think are involved in this question.
_micropost_form.html.erb(The filling up form that would be displayed on the user's home page)
<%= simple_form_for #micropost do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.label :content %><br />
<%= f.text_area :content, placeholder: "Add new task..." %>
</div>
<div class="field">
<%= f.label :tag_list, "Tags (separated by commas)" %><br />
<%= f.text_field :tag_list %>
</div>
<%= f.submit "Add Task", class: "btn btn-primary" %>
<% end %>
micropost.html.erb(for showing the individual micro posts)
<li id="micropost-<%= micropost.id %>">
<%= link_to gravatar_for(micropost.user, size: 50), micropost.user %>
<span class="user"><%= link_to micropost.user.name, user_path(micropost.user) %></span>
<span class="content"><%= micropost.content %></span>
<p><small>Tags: <%= raw micropost.tags.map(&:name).map { |t| link_to t, tag_path(t) }.join(', ') %></small</p>
<span class="timestamp">
Posted <%= time_ago_in_words(micropost.created_at) %> ago.
<% if current_user?(micropost.user) %>
<%= link_to "Done", micropost_path(micropost), method: :delete, data: { confirm: "Keep up the good work!" } %>
<% end %>
</span>
</li>
routes.rb
Rails.application.routes.draw do
resources :users
resources :microposts
get '/about', to: 'static_pages#about'
get '/contact', to: 'static_pages#contact'
get '/signup', to: 'users#new'
post '/signup', to: 'users#create'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
get '/users/admin', to: 'users#admin'
get 'tags/:tag', to: 'microposts#index', as: :tag
root 'static_pages#home'
end
micropost_controller
class MicropostsController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
before_action :correct_user, only: :destroy
def index
params[:tag] ? #microposts = Micropost.tagged_with(params[:tag]) : #microposts = Micropost.all
end
def show
#micropost = Micropost.find(params[:id])
end
def create
#micropost = current_user.microposts.build(micropost_params)
if #micropost.save
flash[:success] = "Micropost created!"
redirect_to root_url
else
#feed_items = []
render 'static_pages/home'
end
end
def destroy
#micropost.destroy
flash[:success] = "You have deleted a task!"
redirect_to request.referrer || root_url
end
private
def micropost_params
params.require(:micropost).permit(:content, :tag_list, :tag,
{tag_ids: [] }, :tag_ids)
end
def correct_user
#micropost = current_user.microposts.find_by(id: params[:id])
redirect_to root_url if #micropost.nil?
end
end
Micropost model
class Micropost < ApplicationRecord
belongs_to :user
has_many :taggings
has_many :tags, through: :taggings
default_scope -> { order(created_at: :desc) }
validates :user_id, presence: true
validates :content, presence: true, length: {maximum: 140 }
attr_accessor :tag_list
def self.tagged_with(name)
Tag.find_by!(name: name).microposts
end
def self.tag_counts
Tag.select('tags.*, count(taggings.tag_id) as count')
.joins(:taggings).group('taggings.tag_id')
end
def tag_list
tags.map(&:name).join(', ')
end
def tag_list=(names)
self.tags = names.split(',').map do |n|
Tag.where(name: n.strip).first_or_create!
end
end
end
Tag model
class Tag < ApplicationRecord
attr_accessor :name
has_many :taggings
has_many :microposts, through: :taggings
end
static_pages controller
class StaticPagesController < ApplicationController
def home
if logged_in?
#micropost = current_user.microposts.build
#feed_items = current_user.feed.paginate(page: params[:page])
end
end
def help
end
def about
end
def contact
end
end
feed.html.erb
<% if #feed_items.any? %>
<ol class="microposts">
<%= render #feed_items %>
</ol>
<%= will_paginate #feed_items %>
<% end %>
I got the following error
ActionController::UrlGenerationError in StaticPages#home
No route matches {:action=>"index", :controller=>"microposts", :tag=>nil}, missing required keys: [:tag]
app/views/microposts/_micropost.html.erb:5:in `block in _app_views_microposts__micropost_html_erb___3891111682689684005_70324923859580'
app/views/microposts/_micropost.html.erb:5:in `map'
app/views/microposts/_micropost.html.erb:5:in `_app_views_microposts__micropost_html_erb___3891111682689684005_70324923859580'
app/views/shared/_feed.html.erb:3:in `_app_views_shared__feed_html_erb__3168328449514417483_70324923896060'
app/views/static_pages/home.html.erb:13:in `_app_views_static_pages_home_html_erb__3511776991923566869_70324898321240'
Can anyone suggest what might be wrong here? Please let me know if more information is needed.
Update: I have implemented some of the changes provided by the answer below, but still has not understood why :tag is not detected, and why the code in red is actually highlighted.
ActionController::UrlGenerationError in StaticPages#home
No route matches {:action=>"index", :controller=>"microposts", :tag=>nil}, missing required keys: [:tag]
The problem is you don't have an index route for your microposts.
Rails.application.routes.draw do
root 'static_pages#home'
get '/readme', to: 'static_pages#readme'
get '/about', to: 'static_pages#about'
get '/contact', to: 'static_pages#contact'
get '/signup', to: 'users#new'
post '/signup', to: 'users#create'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
get '/users/admin', to: 'users#admin'
resources :users
resources :microposts, only: [:create, :destroy] #Here's the problem
get 'tags/:tag', to: 'microposts#index', as: :tag
end
change to:
resources :microposts, only: [:index, :create, :destroy]
EDIT:
Another problem is
if logged_in?
#micropost = current_user.microposts.build #this just returns a new 1
#feed_items = current_user.feed.paginate(page: params[:page])
end
You probably want something like:
if logged_in?
#microposts = current_user.microposts
#feed_items = Micropost.all.paginate(page: params[:page])
end
This will give you all the user's microposts. Then you iterate through them in your views.
I actually found the cause of the problem to be quite simple. After running rails console, it seems like my db:seed wasn't even raked properly, causing my tags to have nil names and causing me to be unable to find the route. Looking further into Rails console is adding nil instead of values to solve my seed adding problem, I realised I have added attr_accessor, forgetting that normal attributes should be added via the command line into the Migration instead of writing into the Model directly. Removing it according to the post updates my database and the code works.
index.html:
<% #partners.each do |j| %>
<% if j.link == nil %>
<div class="column_left"><%= j.name %></div>
<% else %>
<div class="column_left"><%= image_tag("#{j.link}") %></div>
<% end %>
<div class="column_right"><%= j.description %></div>
<%if logged_in? %>
<%= button_to "-", j, :method => :destroy , data: { confirm: "Sind Sie sich sicher, dass sie den Partner #{j.name} löschen wollen?" } %>
<% end %>
controller:
def delete
Partner.find(partner_params).destroy_all
redirect_to partner_path, notice: "#Eintrag wurde gelöscht!"
end
def addPartner
#partner = Partner.new(partner_params)
if !Partner.exists?(:name => partner_params[:name])
uploaded_io = params[:partner][:logo]
File.open(Rails.root.join('app', 'assets', 'images', 'partner', uploaded_io.original_filename), 'wb') do |file|
file.write(uploaded_io.read)
#partner[:link] = "partner/#{uploaded_io.original_filename}"
params[:partner].delete :logo
#partner.save
redirect_to partner_path, notice: "#{#partner.name} wurde modifiziert!"
end
else
#partner = Partner.where(:name => partner_params[:name])
if #partner.update_all(partner_params)
flash[:notice] = "#{#partner.name} wurde geändert!"
end
end
end
private
def partner_params
params.require(:partner).permit(:name, :link, :description)
end
routes.rb:
Rails.application.routes.draw do
get '/login' => 'sessions#new'
post '/login' => 'sessions#create'
delete '/logout' => 'sessions#destroy'
resources :users
get '/home' => 'main#home'
get '/impressum' => 'main#impressum'
post '/impressum' => 'main#updateImpressumById'
get '/partner' => 'partner#index'
post '/partner' => 'partner#addPartner'
delete '/partner' => 'partner#delete'
get '/jobs' => 'jobs#index'
post '/jobs' => 'jobs#index'
get '/kontakt' => 'contacts#new'
post '/home' => 'main#updateText'
get '/referenzen' => 'reference#index'
post '/referenzen' => 'reference#index'
resources "contacts", only: [:new, :create]
I want to delete an entry from my database by clicking on a button. But there must be a conflict with the "private_params".
I always got this problem:
param is missing or the value is empty: partner
I searched for similiar problems, but nothing seems to fit really.
If you want to delete an entry then you need to send a id of partner
<%if logged_in? %>
<%= button_to "Delete", partner_path(id: j.id), :method => :delete %>
<% end %>
Controller: -
def destroy
Partner.find(params[:id]).destroy_all
redirect_to partner_path, notice: "#Eintrag wurde gelöscht!"
end
Routes: -
Rails.application.routes.draw do
get '/login' => 'sessions#new'
post '/login' => 'sessions#create'
delete '/logout' => 'sessions#destroy'
resources :users
get '/home' => 'main#home'
get '/impressum' => 'main#impressum'
post '/impressum' => 'main#updateImpressumById'
get '/partners' => 'partner#index'
post '/partners' => 'partner#addPartner'
delete '/partner/:id' => 'partner#delete'
get '/jobs' => 'jobs#index'
post '/jobs' => 'jobs#index'
get '/kontakt' => 'contacts#new'
post '/home' => 'main#updateText'
get '/referenzen' => 'reference#index'
post '/referenzen' => 'reference#index'
resources "contacts", only: [:new, :create]
Thanks for the help Gabbar, but now I found the solution on my own. Was a pretty stupid one.
I called
method: destroy
but it must be: method: delete
otherwise the wrong path is chosen.
Then the routes.rb need to be: delete '/partner' => 'partner#delete'
If you only want delete 1 record, use the method destroy like this :
Partner.find(params[:id]).destroy
Now, if you want delete more than 1, use destroy_all passing a condition as an argument, like this :
Partner.destroy_all(status: 'inactive')
So, replace destroy_all with destroyer, like this:
Partner.find(params[:id]).destroy
I hope that helps you
Destroy_all documentation
I'm trying to have subscribers unsubscribe via a delete form where they enter their email and then submit and then delete the subscription. Not sure why this isn't working. I've tried a number of things via my controller. Would love some suggestions or alternatives.
Currently getting this error
Couldn't find Subscription without an ID
Subscriptions controller
def destroy
#subscriptions = Subscription.all
#subscription = #subscriptions.find(params[:id])
if #subscription.email == params[:email]
#subscription.destroy
flash[:notice] = "You have been unsubscribed"
redirect_to root_path
else
end
end
Routes
Rails.application.routes.draw do
get 'password_resets/new'
get 'password_resets/edit'
get 'sessions/new'
get 'users/new'
resources :posts
root 'static_pages#new_home'
resources :subscriptions, only: [:new, :create, :edit, :update, :show, :destroy]
get '/home' => 'static_pages#home'
get 'subscriptions' => 'subscriptions#show'
delete 'subscriptions' => 'subscriptions#destroy'
get '/about' => 'static_pages#about'
get '/author' => 'static_pages#author'
get '/contact' => 'static_pages#contact'
get '/book' => 'static_pages#book'
get '/signup' => 'users#new'
get 'login' => 'sessions#new'
post 'login' => 'sessions#create'
delete 'logout' => 'sessions#destroy'
resources :users
resources :account_activations, only: [:edit]
resources :password_resets, only: [:new, :create, :edit, :update]
resources :posts do
resources :comments
end
end
Unsubscribe partial in subscriptions view
<%= form_for #subscription, method: :delete do |f| %>
<div class="row">
<h2>Unsubscribe</h2>
</div>
<div class="row newsletter">
<form method="post" action="#" class="contact-form">
<div class="row email-label">
<%= f.label :email, :class => 'label-email' %>
<%= f.email_field :email %>
</div>
<div class="row">
<%= f.submit 'Unsubscribe', :class => 'btn-full-subscribe' %>
</div>
</form>
</center
<% end %>
I've tried a number of things with no luck. Help would be appreciated. Thanks. Subscriptions are not related to User model.
This line #subscription = #subscriptions.find(params[:email]) is causing the issue.
Try #subscription = #subscriptions.find_by_email(params[:email]) or better yet, use the id #subscription = #subscriptions.find(params[:id]).
ActiveRecord::find only uses ids: http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-find.
Problem is here
#subscription = #subscriptions.find(params[:email])
because find uses id to fetch the record if you want to fetch by any other field use find_by_"attribute_name", Replace it with
#subscription = Subscription.find_by_email(params[:email])
Or no need to write down extra code. No need to fetch all the subscriptions. To delete use
#subscription = Subscription.find_by_email(params[:email])
or
#subscription = Subscription.find(params[:id])
if #subscription.destroy
flash[:notice] = "You have been unsubscribed"
redirect_to root_path
end
I made a new controller to integrate Stripe Checkout, but it's acting as its own entire website and none of my partials (_header, _footer) are displaying.
The current setups is straight from their tutorial https://stripe.com/docs/checkout/guides/rails
Charges Controller
class ChargesController < ApplicationController
def new
end
def create
# Amount in cents
#amount = 100
customer = Stripe::Customer.create(
:email => params[:stripeEmail],
:source => params[:stripeToken],
:plan => "tier1",
)
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to new_charge_path
end
end
Routes
Rails.application.routes.draw do
get 'password_resets/new'
get 'password_resets/edit'
get 'sessions/new'
root 'static_pages#home'
get 'help' => 'static_pages#help'
get 'about' => 'static_pages#about'
get 'contact' => 'static_pages#contact'
get 'signup' => 'users#new'
get 'login' => 'sessions#new'
post 'login' => 'sessions#create'
delete 'logout' => 'sessions#destroy'
get 'charges' => 'charges#new'
resources :users
resources :account_activations, only: [:edit]
resources :password_resets, only: [:new, :create, :edit, :update]
resources :charges
end
/layouts/charges.html.erb (controller view)
<% provide(:title, 'Edit Billing') %>
<%= yield %>
views/charges/new.html.erb (form with Stripe Checkout on it)
<%= form_tag charges_path do %>
<article>
<% if flash[:error].present? %>
<div id="error_explanation">
<p><%= flash[:error] %></p>
</div>
<% end %>
<label class="amount">
<span>Amount: $1.00</span>
</label>
</article>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="<%= Rails.configuration.stripe[:publishable_key] %>"
data-description="Tier 1 Monthly Subscription"
data-amount="100"
data-locale="auto"
data-image="images/marketplace.png"
data-name="Pallet Tier 1"
data-description="Tier 1 Monthly Subscription"
data-label="Join" >
</script>
views/charges/create.html.erb (redirect after successful charge)
<% provide(:title, 'Edit Billing') %>
<h2>Thanks, you paid <strong>$1.00</strong>!</h2>
I'm quite new to Ruby on Rails and I'm trying to learn a bit, so I tried making a new function.
The error I'm getting right now is:
ActionController::RoutingError (No route matches [POST] "/users/2"):
I'm trying to make a function to promote other users to admin, which is only possible as an admin.
My users_controller.rb contains:
def promote
if !User.find(params[:id]).admin?
User.find(params[:id]).toggle!(:admin)
flash[:success] = "User is promoted to admin."
redirect_to users_url
else
flash[:danger] = "Admins can't demote other admins."
redirect_to users_url
end
end
My _user.html.erb contains:
<%= link_to user.name, user %>
<% if current_user.admin? && !current_user?(user) %>
<% if !user.admin? %>
<br /> <%= link_to "Delete User", user, method: :delete,
data: { confirm: "You sure?" } %>
| <%= link_to "Promote to Admin", user, method: :promote,
data: { confirm: "You sure?" } %>
<% end %>
<% end %>
And then we have my routes.rb, which contains:
Rails.application.routes.draw do
get 'password_resets/new'
get 'password_resets/edit'
get 'sessions/new'
get 'users/new'
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
root 'static_pages#home'
get 'help' => 'static_pages#help'
get 'about' => 'static_pages#about'
get 'contact' => 'static_pages#contact'
get 'signup' => 'users#new'
get 'login' => 'sessions#new'
post 'login' => 'sessions#create'
delete 'logout' => 'sessions#destroy'
resources :users do
member do
get :following, :followers
end
end
resources :users
resources :account_activations, only: [:edit]
resources :password_resets, only: [:new, :create, :edit, :update]
resources :microposts, only: [:create, :destroy]
resources :relationships, only: [:create, :destroy]
end
I can't exactly find what's going wrong. Some advice would be awesome!
def promote
#user = User.find(params[:id])
if #user.admin?
#user.toggle!(:admin)
flash[:success] = "User is promoted to admin."
redirect_to users_path
else
flash[:notice] = "Admins can't demote other admins."
redirect_to users_path
end
end
<%= link_to #user.name, #user %>
<% if current_user.admin? && !current_user?(#user) %>
<% if !#user.admin? %>
<br />
<%= link_to "Delete User", #user, method: :delete, data: { confirm: "You sure?" } %>
| <%= link_to "Promote to Admin", promote_users_path(user), method: :put, data: { confirm: "You sure?" } %>
<% end %>
<% end %>
in route
resources :users do
member do
get :following, :followers,
put :promote
end
end
or
match '/users', to: 'users#promote', via: :put