Ruby error with form - ruby-on-rails

how to make route from appointment/new51 action to create51 action ? because it automatically redirect me to create and I don't want this. I am new in Ruby and I have lots of problems with my school project but it is almost finished:)
Routes.rb:
ZOZ::Application.routes.draw do
resources :refferals do
collection do
get 'new51'
end
member do
get 'show'
end
end
#17 potwierdzanie rejestracji
resources :appointments do
collection do
get 'search'
get 'search_result'
get 'to_confirm'
get 'new51'
end
member do
put :confirm
put :create51
end
end
resources :clinics do
collection do
get 'index51'
end
member do
get 'show51s'
end
end
resources :doctors do
collection do
get 'index51a'
get 'index51'
end
member do
get 'show51s'
get 'show51ss'
end
end
resources :patients do
collection do
get 'select51'
get 'index51'
end
member do
get 'show51s'
get 'show51ss'
end
end
get "welcome/index2"
get "welcome/index"
get 'appointments/create'
get 'appointments/move' => 'appointments#move'
post 'appointments/move' => 'appointments#doctors_list'
get 'appointments/move/:id' => 'appointments#doctor_appointments', as: :doctor_appointments
get 'appointments/change_appointment/:id' => 'appointments#change_appointment', as: :change_appointment
get 'appointments/change_doctor_and_appointment/:id' => 'appointments#change_doctor_and_appointment', as: :change_doctor_and_appointment
get 'appointments/success' => 'appointments#success'
# The priority is based upon order of creation:
# first created -> highest priority.
# Sample of regular route:
# match 'products/:id' => 'catalog#view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# Sample resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Sample resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Sample resource route with more complex sub-resources
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', :on => :collection
# end
# end
# Sample resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
root :to => 'welcome#index'
# See how all your routes lay out with "rake routes"
# This is a legacy wild controller route that's not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.
# match ':controller(/:action(/:id))(.:format)'
end
Appointments_controller:
class AppointmentsController < ApplicationController
before_filter :load_appointment, only: [:show, :update, :edit, :destroy]
before_filter :load_wizard, only: [:new, :edit, :create, :update]
def search
end
def new51
#doctors_workplace = DoctorsWorkplace.scoped
#doctors_workplace = #doctors_workplace.where(doctor_id: Doctor.find(session[:current_doctor_id2]).id)
#appointment = Appointment.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #appointment }
end
end
def create51
#appointment = Appointment.new(params[:appointment])
respond_to do |format|
if #appointment.save
format.html { redirect_to #appointment, notice: 'Appointment was successfully created.' }
format.json { render json: #appointment, status: :created, location: #appointment }
else
format.html do
#schedules = Schedule.scoped
#schedules = #schedules.where(doctor_id: Doctor.find(session[:current_doctor_id2]).id)
render action: "new51"
end
format.json { render json: #appointment.errors, status: :unprocessable_entity }
end
end
end
def search_result
d = params[:date]
data = Date.new(d["(1i)"].to_i, d["(2i)"].to_i, d["(3i)"].to_i)
#szukanie pacjenta
#patients = Patient.scoped
#patients = #patients.where(pesel: params[:pesel])
if params[:imie] != ""
#patients = #patients.where(imie: params[:imie])
end
if params[:nazwisko] != ""
#patients = #patients.where(nazwisko: params[:nazwisko])
end
#szukanie doctora
opcja = 0
#doctors = Doctor.scoped
if params[:imie_lekarza] != ""
#doctors = #doctors.where(imie_lekarza: params[:imie_lekarza])
opcja = 1
end
if params[:nazwisko_lekarza] != ""
#doctors = #doctors.where(nazwisko_lekarza: params[:nazwisko_lekarza])
opcja = 1
end
#zlaczenie
#patient_appo = #patients.first.appointments.where(:data_godzina_wizyty => data.beginning_of_day..data.end_of_day, potwierdzona: false)
if opcja == 1
#doctors_appo = #doctors.first.appointments.where(:data_godzina_wizyty => data.beginning_of_day..data.end_of_day, potwierdzona: false)
#appointments = #patient_appo & #doctors_appo
else
#appointments = #patient_appo
end
end
def to_confirm
session['last_search'] = request.env["HTTP_REFERER"]
#appointment = Appointment.find(params[:id])
#patient = Patient.find(#appointment.patient_id)
if #appointment.doctor_id != nil
#doctor = Doctor.find(#appointment.doctor_id)
end
if #appointment.refferal_id != nil
#refferal = Refferal.find(#appointment.refferal_id)
end
end
def confirm
#appointment = Appointment.find(params[:id])
#appointment.potwierdzona = true
if #appointment.save
#redirect_to :back, notice: 'Rejestracja zostala pomyslnie potwierdzona.'
redirect_to session[:last_search], notice: 'Rejestracja zostala pomyslnie potwierdzona.'
else
redirect_to :back, notice: 'Niestety wystapil blad. Prosze sprubowac pozniej'
end
end
def index
#appointments = Appointment.all
end
def show
end
def new
#appointment = #wizard.object
#clinics = Clinic.all
#doctors = Doctor.all
end
public
def findDoctorViaClinic( clinic )
return( (Clinic.find( clinic )).doctors.uniq )
end
helper_method :findDoctorViaClinic
def findScheduleViaDoctor(d)
s = Schedule.includes(:doctors_workplace).where(doctors_workplace_id: (DoctorsWorkplace.includes(:doctor).where(doctor_id: d)) ).where(taken: 0)
return s
end
helper_method :findScheduleViaDoctor
def edit
end
def create
#appointment = #wizard.object
if #wizard.save
s = ( Schedule.find( #appointment.schedule.id ) )
s.taken = true
s.save
redirect_to #appointment, notice: "Appointment saved!"
else
render :new
end
end
def update
if #wizard.save
redirect_to #appointment, notice: 'Appointment was successfully updated.'
else
render action: 'edit'
end
end
def destroy
#appointment.destroy
redirect_to appointments_url
end
private
def load_appointment
#appointment = Appointment.find(params[:id])
end
def load_wizard
#wizard = ModelWizard.new(#appointment || Appointment, session, params)
if self.action_name.in? %w[new edit]
#wizard.start
elsif self.action_name.in? %w[create update]
#wizard.process
end
end
end
_form51:
<%= form_for(#appointment) do |f| %>
<% if #appointment.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#appointment.errors.count, "error") %> prohibited this appointment from being saved:</h2>
<ul>
<% #appointment.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :data_godzina_wizyty %><br />
<%=
options = { start_year: 2.year.from_now.year,
end_year: 2013,
include_blank: true,
default: nil }
f.datetime_select :data_godzina_wizyty, options
%>
<!--<input type="text" data-behaviour='datepicker' :data_wizyty > -->
</div>
<div class="field">
<%= f.hidden_field :doctor_id, :value => Doctor.find(session[:current_doctor_id2]).id %>
</div>
<div class="field">
<%= f.hidden_field :patient_id, :value => Patient.find(session[:current_patient_id]).id %>
</div>
<div class="actions">
<%= submit_tag "Utworz wizyte" %>
</div>
<% end %>

wymaga_Potwierdzenia != wymaga_potwierdzenia
Correct to the right method/column name.

Related

NoMethodError in Refinery::Blog::Posts#index

When I want to go to "localhost:3000/blog" the web page gives this error...
Showing C:/Sites/ifurniture/app/views/refinery/blog/posts/index.html.erb where line #3 raised:
undefined method `to_sym' for {:title=>"Body", :slug=>"body"}:Hash
Rails.root: C:/Sites/ifurniture
this is the blog controller..
module Refinery
module Blog
class PostsController < BlogController
before_filter :find_all_blog_posts, :except => [:archive]
before_filter :find_blog_post, :only => [:show, :comment, :update_nav]
before_filter :find_tags
respond_to :html, :js, :rss
def index
if request.format.rss?
#posts = if params["max_results"].present?
# limit rss feed for services (like feedburner) who have max size
Post.recent(params["max_results"])
else
Post.newest_first.live.includes(:comments, :categories)
end
end
respond_with (#posts) do |format|
format.html
format.rss { render :layout => false }
end
end
def show
#comment = Comment.new
#canonical = refinery.url_for(:locale => Refinery::I18n.current_frontend_locale) if canonical?
#post.increment!(:access_count, 1)
respond_with (#post) do |format|
format.html { present(#post) }
format.js { render :partial => 'post', :layout => false }
end
end
def comment
#comment = #post.comments.create(comment_params)
if #comment.valid?
if Comment::Moderation.enabled? or #comment.ham?
begin
CommentMailer.notification(#comment, request).deliver_now
rescue
logger.warn "There was an error delivering a blog comment notification.\n#{$!}\n"
end
end
if Comment::Moderation.enabled?
flash[:notice] = t('thank_you_moderated', :scope => 'refinery.blog.posts.comments')
redirect_to refinery.blog_post_url(params[:id])
else
flash[:notice] = t('thank_you', :scope => 'refinery.blog.posts.comments')
redirect_to refinery.blog_post_url(params[:id],
:anchor => "comment-#{#comment.to_param}")
end
else
render :show
end
end
def archive
if params[:month].present?
date = "#{params[:month]}/#{params[:year]}"
archive_date = Time.parse(date)
#date_title = ::I18n.l(archive_date, :format => '%B %Y')
#posts = Post.live.by_month(archive_date).page(params[:page])
else
date = "01/#{params[:year]}"
archive_date = Time.parse(date)
#date_title = ::I18n.l(archive_date, :format => '%Y')
#posts = Post.live.by_year(archive_date).page(params[:page])
end
respond_with (#posts)
end
def tagged
#tag = ActsAsTaggableOn::Tag.find(params[:tag_id])
#tag_name = #tag.name
#posts = Post.live.tagged_with(#tag_name).page(params[:page])
end
private
def comment_params
params.require(:comment).permit(:name, :email, :message)
end
protected
def canonical?
Refinery::I18n.default_frontend_locale != Refinery::I18n.current_frontend_locale
end
end
end
end
the post controller...
module Refinery
module Blog
class PostsController < BlogController
before_filter :find_all_blog_posts, :except => [:archive]
before_filter :find_blog_post, :only => [:show, :comment, :update_nav]
before_filter :find_tags
respond_to :html, :js, :rss
def index
if request.format.rss?
#posts = if params["max_results"].present?
# limit rss feed for services (like feedburner) who have max size
Post.recent(params["max_results"])
else
Post.newest_first.live.includes(:comments, :categories)
end
end
respond_with (#posts) do |format|
format.html
format.rss { render :layout => false }
end
end
def show
#comment = Comment.new
#canonical = refinery.url_for(:locale => Refinery::I18n.current_frontend_locale) if canonical?
#post.increment!(:access_count, 1)
respond_with (#post) do |format|
format.html { present(#post) }
format.js { render :partial => 'post', :layout => false }
end
end
def comment
#comment = #post.comments.create(comment_params)
if #comment.valid?
if Comment::Moderation.enabled? or #comment.ham?
begin
CommentMailer.notification(#comment, request).deliver_now
rescue
logger.warn "There was an error delivering a blog comment notification.\n#{$!}\n"
end
end
if Comment::Moderation.enabled?
flash[:notice] = t('thank_you_moderated', :scope => 'refinery.blog.posts.comments')
redirect_to refinery.blog_post_url(params[:id])
else
flash[:notice] = t('thank_you', :scope => 'refinery.blog.posts.comments')
redirect_to refinery.blog_post_url(params[:id],
:anchor => "comment-#{#comment.to_param}")
end
else
render :show
end
end
def archive
if params[:month].present?
date = "#{params[:month]}/#{params[:year]}"
archive_date = Time.parse(date)
#date_title = ::I18n.l(archive_date, :format => '%B %Y')
#posts = Post.live.by_month(archive_date).page(params[:page])
else
date = "01/#{params[:year]}"
archive_date = Time.parse(date)
#date_title = ::I18n.l(archive_date, :format => '%Y')
#posts = Post.live.by_year(archive_date).page(params[:page])
end
respond_with (#posts)
end
def tagged
#tag = ActsAsTaggableOn::Tag.find(params[:tag_id])
#tag_name = #tag.name
#posts = Post.live.tagged_with(#tag_name).page(params[:page])
end
private
def comment_params
params.require(:comment).permit(:name, :email, :message)
end
protected
def canonical?
Refinery::I18n.default_frontend_locale != Refinery::I18n.current_frontend_locale
end
end
end
end
and this is the index.html.erb of Blog.
<section class="container">
<% content_for :body do %>
<%= raw #page.content_for(Refinery::Pages.default_parts.first.to_sym) if Refinery::Pages.default_parts.any? %>
<% if #posts.any? %>
<section id="blog_posts" class="news">
<%= render :partial => "/refinery/blog/shared/post", :collection => #posts %>
<%= will_paginate #posts %>
</section>
<% else %>
<p><%= t('.no_blog_articles_yet') %></p>
<% end %>
<% end %>
<% content_for :side_body_prepend do -%>
<%= raw #page.content_for(Refinery::Pages.default_parts.second.to_sym) %>
<% end if Refinery::Pages.default_parts.many? -%>
<%= render "/refinery/content_page" %>
<% content_for :stylesheets, stylesheet_link_tag('refinery/blog/frontend') %>
</section>
I'll be watching for your help, thanks.
You can use to_sym method on hash or string so in your code you can do something like this:
index.html
instead this:
<%= raw #page.content_for(Refinery::Pages.default_parts.first.to_sym) if Refinery::Pages.default_parts.any? %>
put this:
<%= raw #page.content_for(Refinery::Pages.default_parts.first[:title].to_sym) if Refinery::Pages.default_parts.any? %>
instead [:title]you can also use [:slug]

Ruby on Rails/How to Scaffold form link to specific action?

My scaffold model doesn't work well with create action.
I found out that if I press submit button, it is linked to TalksController#index but it should be linked to TalksController#create
I don't know how I can fix it to link to create action. There aren't any codes related to it in _form.html.erb and new.html.erb
Create worked well 2 days ago.
[edit]I post my codes.
I added some codes in addition to the codes scaffold made itself
talks_controller.rb
class TalksController < ApplicationController
before_action :set_talk, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [ :index, :show, :all ]
# GET /talks
# GET /talks.json
def all
#talks = Talk.all
#talks = Talk.order(created_at: :desc)
end
def index
#talks = Talk.all
#talks = Talk.order(created_at: :desc)
#whichboard = params[:whichboard]
#seq = params[:saveit]
#title = params[:savetitle]
end
# GET /talks/1
# GET /talks/1.json
def show
end
# GET /talks/new
def new
#talk = Talk.new
#seq = params[:seq]
#whichboard = params[:whichboard]
end
# GET /talks/1/edit
def edit
authorize_action_for #talk
end
# POST /talks
# POST /talks.json
def create
#talk = Talk.new(talk_params)
#talk.user_id = current_user
#talk.seq = params[:talk][:seq]
#talk.where = params[:talk][:where]
respond_to do |format|
if #talk.save
format.html { redirect_to #talk, notice: 'Talk was successfully created.' }
format.json { render :index, status: :created, location: #talk }
else
format.html { render :new }
format.json { render json: #talk.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /talks/1
# PATCH/PUT /talks/1.json
def update
authorize_action_for #talk
respond_to do |format|
if #talk.update(talk_params)
format.html { redirect_to #talk, notice: 'Talk was successfully updated.' }
format.json { render :show, status: :ok, location: #talk }
else
format.html { render :edit }
format.json { render json: #talk.errors, status: :unprocessable_entity }
end
end
end
# DELETE /talks/1
# DELETE /talks/1.json
def destroy
authorize_action_for #talk
#talk.destroy
respond_to do |format|
format.html { redirect_to talks_url, notice: 'Talk was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_talk
#talk = Talk.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def talk_params
params.require(:talk).permit(:content, :user_id, :seq, :where)
end
end
_form.html.erb
<%= simple_form_for(#talk) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :content %>
<%#= f.association :user %>
<%= f.input :seq, :as => :hidden, :input_html => { :value => #seq } %>
<%= f.input :where, :as => :hidden, :input_html => { :value => #whichboard } %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
new.html.erb
<div class="row">
<div class='col-md-12'>
<p style='text-align:right;'>
created by <%= current_user.name %>, Current Time : <%= Time.now %>, board <%= #whichboard %> seq <%= #seq %>
</p>
</div>
</div>
<%= render 'form' %>
<%= link_to 'Back', talks_path %>
[SECOND EDIT] routes.rb
Rails.application.routes.draw do
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
root 'cpu#index'
post ':controller(/:action(/:id(.:format)))'
get ':controller(/:action(/:id(.:format)))'
resources :talks
end
adjust your routes.rb
Rails.application.routes.draw do
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
root 'cpu#index'
resources :talks
#do you really need these?
post ':controller(/:action(/:id(.:format)))'
get ':controller(/:action(/:id(.:format)))'
end
to put the resources :talks above the default/catchall routes. the routes are processed on first match, so if you need those default/catchalls youcan put them at the bottom. That being said, unless you have a requirement for them most modern rails apps don't require them by default, so you can probably comment out / remove them as another option.
The index and create both refer to the same url or the same route method, the only difference is the method if you use the method as post then, it'll go to create otherwise it goes to index. But, you could implicitly handle this if you pass in the new instance of the object you are trying to create such as #customer = Customer.new then, pass #customer to the form_for method.
With the form_for method, you can specify url of the action you want to be executed or just controller and action like this:
<%= form_for #post, :url => {:controller => "your-controller-name", :action => "your-action-name"} do |f| %>
And in your action ("your-action-name") you can call your parameters like:
post_id = params[:post][:id]
Hope that will help you.

Rails, after remote delete of item I get: First argument in form cannot contain nil or be empty

I want to delete an image on click.
This is in my view
<%=form_for #area, url: areas_update_path, remote: true, html: {class: "form-horizontal",:multipart => true} do |f|%>
....
<% #area.area_attachments.each do |a| %>
<%unless a.image.blank?%>
<%= link_to delete_area_attachment_path(a), :remote => true, :method => :delete do%>
<%= image_tag a.image_url(:thumb), class:"delete-image" %>
<% end %>
<% end %>
<% end %>
....
<% end %>
After I click on an image, the image gets deleted, but I get
First argument in form cannot contain nil or be empty
In the first line of the code that I posted (#area I guess)
My delete_area_attachment method in my area_attachments_controller
def delete_area_attachment
#areaAttachment = AreaAttachment.find(params[:id])
#areaAttachment.destroy
respond_to do |format|
format.js
end
end
I guess the #area variable has to be initialized, but why?
What I am trying to delete is an area_attachment not an area, and I already initialized it, so what does the #area variable has to do with that?
How do I go about it here?
EDIT:
my relative routes:
#Area Paths
get '/areas/new', to: 'areas#new', :as => 'areas_new'
post '/areas/create', to: 'areas#create', :as => 'areas_create'
get '/areas/:id/destroy', to: 'areas#destroy', :as => 'areas_destroy'
delete 'delete_area/:id', controller: 'areas', action: 'delete_area'
get '/areas/:id/edit', to: 'areas#edit', :as => 'areas_edit'
patch '/areas/:id/update', to: 'areas#update', :as => 'areas_update'
#Area Attachment Paths
delete 'delete_area_attachment/:id', controller: 'area_attachments', action: 'delete_area_attachment', :as => 'delete_area_attachment'
My areas_controller
class AreasController < ApplicationController
before_action :set_areas
before_action :set_area, only: [:edit, :delete, :update, :destroy]
def new
#area = Area.new
#languages = Language.all
#area_attachment = #area.area_attachments.build
end
def create
#area = Area.new(area_params)
if #area.save && manage_strings
params[:area_attachments]['image'].each do |a|
#area_attachment = #area.area_attachments.create!(:image => a, :area_id => #area.id)
end
#status = 'success'
else
#status = 'error'
#errormessages = #area.errors.full_messages
end
respond_to do |format|
format.js
end
end
def edit
end
def update
if #area.update(area_params) && manage_strings
params[:area_attachments]['image'].each do |a|
#area_attachment = #area.area_attachments.create!(:image => a, :area_id => #area.id)
end
#status = 'success'
else
#status = 'error'
#errormessages = #area.errors.full_messages
end
respond_to do |format|
format.js
end
end
def delete_area
#area = Area.find(params[:id])
#area.destroy
respond_to do |format|
format.js
end
end
def find_area_by_id
area = Area.find(params[:id])
render json: area
end
protected
def news_list
respond_to do |format|
format.js
end
end
private
def area_params
params.require(:area).permit(:id, area_attachments_attributes: [:id, :area_id, :image])
end
def set_area
#area = Area.find_by_id(params[:id])
#languages = Language.all
#area_attachments = #area.area_attachments.all
end
def set_areas
#areas = Area.all
end
def manage_strings
if params[:area][:strings].any?
params[:area][:strings].each do |key,value|
string = #area.article_localizations.find_or_initialize_by(:language_id => key.to_i)
string.title = params[:area][:strings][key][:title]
string.text = params[:area][:strings][key][:text]
string.save
end
end
end
end
In delete_area_attachment before #areaAttachment.destroy add:
#area = Area.find_by_id(#areaAttachment.area_id)

ransack search is missing a param

I am trying to create search form using ransack on rails. I have run into a small problem.
I get an error
param is missing or the value is empty: information
When I submit the search.
Information_controller.rb
class InformationController < ApplicationController
before_action :set_information, only: [:show, :edit, :update, :destroy]
respond_to :html
# Add the breadcrumbs
require 'uri'
# User must authenticate to use all actions in the users controller
before_filter :authenticate_user!, except: [ :home, :show, :splash]
def index
#search = Information.search(params[:q])
#information = params[:distinct].to_i.zero? ?
#search.result :
#search.result(distinct: true)
#information = #information.page(params[:page]).per(10)
respond_with #information
end
def admin
#search = Information.search(params[:q])
#information = #search.result
#search.build_condition
end
#def search
##q = Information.ransack(params[:q])
##information = #q.result(distinct: true)
#end
# GET /information/1
# GET /information/1.json
def show
session[:return_to] = request.fullpath
end
# GET /information/new
def new
#information = Information.new
end
# GET /information/1/edit
def edit
end
# POST /information
# POST /information.json
def create
#information = Information.new(information_params)
respond_to do |format|
if #information.save
format.html { redirect_to #information, notice: 'Entry was successfully created.' }
format.json { render :show, status: :created, location: #information }
else
format.html { render :new }
format.json { render json: #information.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /information/1
# PATCH/PUT /information/1.json
def update
respond_to do |format|
if #information.update(information_params)
format.html { redirect_to #information, notice: 'Entry was successfully updated.' }
format.json { render :show, status: :ok, location: #information }
else
format.html { render :edit }
format.json { render json: #information.errors, status: :unprocessable_entity }
end
end
end
# DELETE /information/1
# DELETE /information/1.json
def destroy
#information.destroy
respond_to do |format|
format.html { redirect_to information_index_url, notice: 'Entry was successfully removed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_information
#information = Information.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def information_params
params.require(:information).permit(:name, :description, :show, :date, :heading, :subheading, :image, :places, :data_type, :reference)
end
end
Search form
<%= search_form_for(
#search,
:url => admin_index_path,
html: { method: :post }
) do |f| %>
<%= f.condition_fields do |c| %>
<%= render "condition_fields", f: c%>
<% end %>
<p><%= link_to_add_fields "Add Conditions", f, :condition %>
<div class="actions"><%= f.submit "Search" %></div>
<% end %>
routes
Rails.application.routes.draw do
root :to => 'information#splash'
devise_for :users, :skip => [:sessions], :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
as :user do
get 'signin' => 'devise/sessions#new', :as => :new_user_session
post 'signin' => 'devise/sessions#create', :as => :user_session
delete 'signout' => 'devise/sessions#destroy', :as => :destroy_user_session
end
##########################################
# ADMIN #
##########################################
#admin panel
get '/admin' => 'information#admin'
#get '/admin/new' => 'information'
resources :information, path: '/admin'
get '/home/:id', to: 'information#show'
get 'home' => 'information#index', :as => :home
concern :paginatable do
get '(page/:page)', :action => :index, :on => :collection, :as => ''
end
concern :paginatable do
get '(page/:page)', :action => :information, :on => :collection, :as => ''
end
#get '/new' => 'information#new'
#get '/public' => 'information#'
##########################################################
resources :information
resources :admin
end
Thank you. If you need more details please ask :^)

Namespace and Simple_Form Hitting The Right Controller/Action

I have a form on a cart page to update line_items. So the resource I am updating needs to exit the cart controller and enter the line_items controller... I am using the following form...
<%= simple_form_for shifted_commerce_line_item_path(item),
:url => {controller: 'line_items', action: 'update'} do |f| %>
I get no route matches...
No route matches {:action=>"update", :controller=>"shifted_commerce/line_items"}
The thing is... I have the the action in the controller...
I'll post my routes.
shifted_commerce_line_items GET /shifted_commerce/line_items(.:format) shifted_commerce/line_items#index
POST /shifted_commerce/line_items(.:format) shifted_commerce/line_items#create
new_shifted_commerce_line_item GET /shifted_commerce/line_items/new(.:format) shifted_commerce/line_items#new
edit_shifted_commerce_line_item GET /shifted_commerce/line_items/:id/edit(.:format) shifted_commerce/line_items#edit
shifted_commerce_line_item GET /shifted_commerce/line_items/:id(.:format) shifted_commerce/line_items#show
PATCH /shifted_commerce/line_items/:id(.:format) shifted_commerce/line_items#update
PUT /shifted_commerce/line_items/:id(.:format) shifted_commerce/line_items#update
DELETE /shifted_commerce/line_items/:id(.:format) shifted_commerce/line_items#destroy
How do I get this form to hit the update action in my controller?
Don't we see the above route? both PUT and PATCH match /shifted_commerce/Line_items/:id...and I'm passing the id with the (item)...
Update 1 I'll also add that I'm running this form in a loop, so every line_item can be edited. #anything isn't what I'd want to pass to the path for an ID... also, I'm operating from the carts controller, in the show action. Not a line_item controller, edit action.
Update 2 If I do the following simple_form_for:
<%= simple_form_for shifted_commerce_line_item_path(item), :url => {controller: 'line_items', action: 'create'} do |f| %>
It successfully takes me into the create action of the line_items controller. But if I do
<%= simple_form_for shifted_commerce_line_item_path(item), :url => {controller: 'line_items', action: 'update'} do |f| %>
I get the route error. What's the deal?! Why does it work for create but not for update? I have the update action in my controller...
ShiftedCommerce::LineItemsController
class ShiftedCommerce::LineItemsController < ApplicationController
before_action :set_line_item, only: [:show, :edit, :update, :destroy]
before_action :set_line_item_item, only: [:show, :edit, :update, :destroy]
# GET /line_items
# GET /line_items.json
def index
#line_items = ShiftedCommerce::LineItem.all
end
# GET /line_items/1
# GET /line_items/1.json
def show
end
# GET /line_items/new
def new
#line_item = ShiftedCommerce::LineItem.new
end
# GET /line_items/1/edit
def edit
end
# POST /line_items
# POST /line_items.json
def create
#cart = current_cart
# item is built from base_item, after finding associated product
#base_item_id = params[:shifted_commerce_line_item][:base_item_id]
get_item_id_from_base_item_params
build_line_item
## Does a line item with the same itemt_id already exist in cart?
if #line_item.exists_in_collect?(current_cart.line_items)
#if so, change quantity, check if there's enough stock
if current_cart.where_line_item_with(#item_id).update_quantity(#line_item.quantity) == true
#line_item.destroy
redirect_to shifted_commerce_base_items_path
flash[:success] = "Detected item In Cart, Added Your Amount More to Quantity"
else #otherwise there's not enough product in stock.
redirect_to shifted_commerce_cart_path
flash[:failure] = "Cannot Add To Cart, Not Enough In Stock"
end
else # This product isn't in the cart already let's save it!
if #line_item.have_enough_item? == true # if there is enough stock, save
if #line_item.save
respond_to do |format|
format.html { redirect_to shifted_commerce_base_items_path,
:notice => "Added to Cart." }
format.xml { render :xml => #line_item,
:status => :created, :location => #line_item }
end
else
format.xml { render :xml => #line_item.errors,
:status => :unprocessable_entity }
end
else # not enough stock, not saved.
redirect_to shifted_commerce_base_items_path
if #line_item.item.stock_qty > 0
flash[:failure] = "Sorry! We Only Don't Have Enough In Stock"
else
flash[:failure] = "Sorry! That Item Is Out Stock"
end
end
end
end
# PATCH/PUT /line_items/1
# PATCH/PUT /line_items/1.json
def update
#line_item = ShiftedCommerce::LineItem.find(params[:id])
raise
#line_item.attributes = line_item_params
if #line_item.over_order_cap? #is the quantity over maximum?
flash[:error] = "Contact Us For Orders of This Size -- Quantity Set To Max"
redirect_to cart_path
else # quantity to change to not over maximum.
if #line_item.have_enough_item? == true
#line_item.update(line_item_params)
#did they update quantity to 0?
if #line_item.quantity <= 0
#line_item.destroy
flash[:success] = "Item Removed"
redirect_to :back
else
flash[:success] = "Itemed Updated"
redirect_to cart_path
end
else
redirect_to cart_path
flash[:failure] = "We Don't Have Enough In Stock. Update Failed"
end
end
end
# DELETE /line_items/1
# DELETE /line_items/1.json
def destroy
#line_item.destroy
respond_to do |format|
format.html { redirect_to line_items_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_line_item
#line_item = LineItem.find(params[:id])
end
def set_line_item_item
#line_item_name = #line_item.item.base_item
end
# Never trust parameters from the scary internet, only allow the white list through.
def line_item_params
params.fetch(:shifted_commerce_line_item, {}).permit(:item_id, :cart_id, :order_id, :quantity, :weight, :units)
end
def build_line_item
#line_item = #cart.line_items.build(
:item_id => #item_id,
:order_id => nil,
:weight => params[:shifted_commerce_line_item][:weight],
:quantity => params[:shifted_commerce_line_item][:quantity]
)
end
def get_item_id_from_base_item_params
#item_id = ShiftedCommerce::Item.where(:base_item_id => #base_item_id).where(:size_id => params[:shifted_commerce_line_item][:size]).first.id
end
end
line_item.rb
class ShiftedCommerce::LineItem < ActiveRecord::Base
belongs_to :item
belongs_to :cart
after_create :set_order_weight#, :set_package_dimentions
after_update :set_order_weight#, :set_package_dimentions
#max capactiy here
def have_enough_item?
if self.item.stock_qty >= self.quantity
return true
else
if self.quantity_was == nil
return false
else
self.quantity = self.quantity_was
self.save
return false
end
end
end
def set_order_weight
if
self.cart.nil?
else
self.cart.total_weight = self.cart.line_items.to_a.sum {|item| (item.weight)*(item.quantity)}
self.cart.save
end
end
def over_order_cap?
if self.quantity > 5
self.quantity = 5
self.save
return true
end
return false
end
def update_quantity(qty)
self.quantity += qty
if self.have_enough_item? == true
self.save
end
end
def exists_in_collect?(items)
items.each do |item|
return true if self.item_id == item.item_id
end
return false
end
def set_order_total_units
if
self.cart.nil?
else
self.set_cart_units
self.cart.total_units = self.cart.total_units
self.cart.save
end
end
def total_price
item.base_item.price * quantity
end
end
Routes.rb
namespace :shifted_commerce do
resources :line_items
resources :items
resources :base_items
resource :cart, only: [:show, :update, :destroy] do
resource :order, only: [:show, :create, :update, :edit, :new]
end
end
Change this and try:
<%= simple_form_for item, url: shifted_commerce_line_items_path(item), method: :put do |f| %>
as per you routes
Update:
Sorry it must be post but not put like this:
<%= simple_form_for item, url: shifted_commerce_line_item_path(item), method: :post do |f| %>
Try using <%= simple_form_for ([:shifted_commerce, item]) do |f| %> or
<%= simple_form_for item, :url => shifted_commerce_line_item_path do |f| %>

Resources