cant access edit path in rails - html

currently im accessing my join table directly. the reason im doing this is because i only want the staff to be able to adjust the status
im facing problem with
undefined method order_task_path' for #<#<Class:0x00000009bf62c0>:0x0000000a6d7c70>`
with parameter Parameters:
{"id"=>"1,1"}
i'm able to display the join table according to my need. the problem is when i try to display it in edit.
here is my ordertask controller
class OrdersTasksController < ApplicationController
before_action :set_status, only: [:show]
def index
#orders = Order.all
##status = OrderTask.includes(:task,:order).where(order_id: params[:id])
end
def edit
#status = OrderTask.find(params[:id])
end
def show
end
def update
respond_to do |format|
if #status.update(order_params)
format.html { redirect_to #status, notice: 'Order was successfully updated.' }
format.json { render :show, status: :ok, location: #order }
else
format.html { render :edit }
format.json { render json: #status.errors, status: :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_status
#status = OrderTask.includes(:task).where(order_id: params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def order_params
params.require(:order_task,:order).permit(:id,:order_id,:status)
end
end
my show.html.erb
<p id="notice"><%= notice %></p>
<table class="table table-hover">
<tr>
<td><h4>Order Number : <%= #status.first.order.order_number %></h4>
</td>
</tr>
<tr>
<td>Task
</td>
<td>Status:
</td>
</tr>
<tr>
<% #status.each do |i| %>
<td><%= i.task.task_name %>
</td>
<td><%= i.status %>
</td>
<td><%= link_to 'Edit', edit_orders_task_path(i) %></td>
</tr>
<% end %>
</table>
<%= link_to 'Back', orders_tasks_path %>
my _form.html.erb
<%= form_for(#status) do |f| %>
<% if #status.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#status.errors.count, "error") %> prohibited this order from being saved:</h2>
<ul>
<% #status.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<table class="table table-hover">
<tr>
<td><%= f.label "List of task" %>
</td>
<td><%= f.label "Status" %>
</td>
</tr>
<tr>
<td><%= f.task_id %>
</td>
<td><div class="dropdown">
<%= f.select(:status,['In progress', 'Completed'], {}, {class: "control"})%> </div>
</td>
</tr>
<tr>
<td>
</td>
<td><%= f.submit %>
</td>
</tr>
</table>
<% end %>
and my routes
resources :orders
resources :services
resources :tasks
resources :customers
resources :staffs
resources :orders_tasks
root 'staffs#index'
and lastly my ordertask model
class OrderTask < ActiveRecord::Base
self.primary_key = [:order_id,:task_id]
self.table_name = "Orders_tasks"
belongs_to :order
belongs_to :task
end
hope u guys can give suggestion or something to help me with this. thx in advance.
EDIT
here is my route.rb
C:\Users\Idea\DHMS>rake routes
Prefix Verb URI Pattern Controller#Action
orders GET /orders(.:format) orders#index
POST /orders(.:format) orders#create
new_order GET /orders/new(.:format) orders#new
edit_order GET /orders/:id/edit(.:format) orders#edit
order GET /orders/:id(.:format) orders#show
PATCH /orders/:id(.:format) orders#update
PUT /orders/:id(.:format) orders#update
DELETE /orders/:id(.:format) orders#destroy
services GET /services(.:format) services#index
POST /services(.:format) services#create
new_service GET /services/new(.:format) services#new
edit_service GET /services/:id/edit(.:format) services#edit
service GET /services/:id(.:format) services#show
PATCH /services/:id(.:format) services#update
PUT /services/:id(.:format) services#update
DELETE /services/:id(.:format) services#destroy
tasks GET /tasks(.:format) tasks#index
POST /tasks(.:format) tasks#create
new_task GET /tasks/new(.:format) tasks#new
edit_task GET /tasks/:id/edit(.:format) tasks#edit
task GET /tasks/:id(.:format) tasks#show
PATCH /tasks/:id(.:format) tasks#update
PUT /tasks/:id(.:format) tasks#update
DELETE /tasks/:id(.:format) tasks#destroy
customers GET /customers(.:format) customers#index
POST /customers(.:format) customers#create
new_customer GET /customers/new(.:format) customers#new
edit_customer GET /customers/:id/edit(.:format) customers#edit
customer GET /customers/:id(.:format) customers#show
PATCH /customers/:id(.:format) customers#update
PUT /customers/:id(.:format) customers#update
DELETE /customers/:id(.:format) customers#destroy
staffs GET /staffs(.:format) staffs#index
POST /staffs(.:format) staffs#create
new_staff GET /staffs/new(.:format) staffs#new
edit_staff GET /staffs/:id/edit(.:format) staffs#edit
staff GET /staffs/:id(.:format) staffs#show
PATCH /staffs/:id(.:format) staffs#update
PUT /staffs/:id(.:format) staffs#update
DELETE /staffs/:id(.:format) staffs#destroy
orders_tasks GET /orders_tasks(.:format) orders_tasks#index
POST /orders_tasks(.:format) orders_tasks#create
new_orders_task GET /orders_tasks/new(.:format) orders_tasks#new
edit_orders_task GET /orders_tasks/:id/edit(.:format) orders_tasks#edit
orders_task GET /orders_tasks/:id(.:format) orders_tasks#show
PATCH /orders_tasks/:id(.:format) orders_tasks#update
PUT /orders_tasks/:id(.:format) orders_tasks#update
DELETE /orders_tasks/:id(.:format) orders_tasks#destroy
root GET / staffs#index

According to the error message undefined method order_task_path' for #<#<Class:0x00000009bf62c0>:0x0000000a6d7c70>, the url helper method does not exist.
you can rake rake routes in the terminal to get all the routes and route helpers.
resources :orders do
resources :tasks
end
generate the following routes and helpers.
order_tasks GET /orders/:order_id/tasks(.:format) tasks#index
POST /orders/:order_id/tasks(.:format) tasks#create
new_order_task GET /orders/:order_id/tasks/new(.:format) tasks#new
edit_order_task GET /orders/:order_id/tasks/:id/edit(.:format) tasks#edit
order_task GET /orders/:order_id/tasks/:id(.:format) tasks#show
PATCH /orders/:order_id/tasks/:id(.:format) tasks#update
PUT /orders/:order_id/tasks/:id(.:format) tasks#update
DELETE /orders/:order_id/tasks/:id(.:format) tasks#destroy
resources :orders do
resources :orders_tasks
end
generate the following routes and helpers.
order_orders_tasks GET /orders/:order_id/orders_tasks(.:format) orders_tasks#index
POST /orders/:order_id/orders_tasks(.:format) orders_tasks#create
new_order_orders_task GET /orders/:order_id/orders_tasks/new(.:format) orders_tasks#new
edit_order_orders_task GET /orders/:order_id/orders_tasks/:id/edit(.:format) orders_tasks#edit
order_orders_task GET /orders/:order_id/orders_tasks/:id(.:format) orders_tasks#show
PATCH /orders/:order_id/orders_tasks/:id(.:format) orders_tasks#update
PUT /orders/:order_id/orders_tasks/:id(.:format) orders_tasks#update
DELETE /orders/:order_id/orders_tasks/:id(.:format) orders_tasks#destroy
http://guides.rubyonrails.org/routing.html#nested-resources

Related

Rails form for editing a collection

What I am trying to accomplish is a simple "toggle" checkbox for On/Off for a view which contains records from a model.
I have attempted to look into a "hidden" value, but it doesn't appear to work as intended.
How to get blank checkboxes to pass as false to params
When I've added: <%= hidden_field_tag "category_ids[]", '' %>
I receive Couldn't find Category with 'category_name'= when unchecking.
Essentially, the table is a Model.all, but I want to be able to modify the key value on an is_active column to true or false, depending on if the box is checked, or not. Currently, I can accomplish this for "checking" the box. But, not unchecking (passes null). I am trying accomplish this is one swoop rather than making all my checkes, and another pass for my unchecked. And, also bypassing the show/edit process. The table size is rather small, so I am not concerned with latency.
I have attempted to search as much as I could, but am at a loss. With what I've found I can do one or the other, but not both unfortunately, and I would greatly appreciate any guidance.
My view:
<h4>Categories</h4>
<%= form_tag enable_categories_path, method: :put do |f| %>
<table id="myTable" class="table table-bordered table-striped">
<tr>
<th>Enable</th>
<th>Category Name</th>
<th>Active</th>
</tr>
<tbody>
<% #categories.each do |category| %>
<tr>
<td>
<%= check_box_tag "category_ids[]", category.id, category.is_active == 1 ? 'checked' : nil %>
</td>
<td><%= link_to category.category_name, category %></td>
<td><%= category.is_active == 1 ? 'Yes' : 'No' %></td>
</tr>
<% end %>
</tbody>
</table>
<%= render 'settings/button' %>
<% end %>
Here, the checkboxes are grabbing their state from the model itself for the corresponding record, so if no action is taken on the checkbox it remains the same (or passes state back)
My controller:
class CategoriesController < ApplicationController
before_action :set_category, only: [:show, :edit, :update]
def index
#categories = Category.all.order(:category_sort)
end
def show
#category = Category.find(params[:id])
end
def edit
end
def update
if #category.update(category_params)
redirect_to categories_path
else
render :edit
end
end
def enable
Category.update(params[:category_ids], params[:category_ids].map{ |e| {is_active: true} })
redirect_to categories_path
end
private
def set_category
#category = Category.find(params[:id])
end
def category_params
params[:category].permit(:id, :category_name, :is_active)
end
end
Currently, I'm only passing is_active: true, until I can figure a way to pass ALL checkbox states.
My model:
class Category < ActiveRecord::Base
self.table_name = 'categories'
has_many :metrics
end
My route:
resources :categories do
collection do
put :toggle
end
end
Everything appears to pass correctly for checked boxes. But, nothing appears in the logs for when something is unchecked.
When I've run into situations like this in Rails I usually end up using AJAX rather than mass assignment. It's actually rather easy. At least easier for me than learning the inner workings of the check_boxes and collection_check_boxes, LOL
A simple Categories table:
<table>
<thead>
<tr>
<th>Category</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<% #categories.each do |category| %>
<tr>
<td><%= category.category_name %></td>
<% status = category.is_active? ? 'Active' : 'Inactive' %>
<td id="<%= category.id %>" ><button class="button_<%= status %>"><%= link_to status, toggle_active_path(:id => category.id), :method => :post, :remote => true %></button></td>
</tr>
<% end %>
</tbody>
</table>
The lines to note are the embedded ruby setting the status variable. This is used to set the value of the class for the button. In the CSS file the button class button_Active sets the color to green and button_Inactive makes it red. It also uses this variable to set the text of the button.
Create a method in the controller that toggles the status:
def toggle_is_active
#category.toggle!(:is_active) #flips the boolean on is_active
respond_to do |format|
format.html { redirect_to(#category) }
format.js
end
Be aware that .toggle! will bypass model validations and save. If you need to ensure validations run you can use #category.toggle(:is_active).save
This will respond to format.js and call a very small file called toggle_is_active.js.erb:
$('#<%= #category.id %>').html('<%= escape_javascript(render :partial => 'toggle_active') %>');
This targets the id of the html element that we set to the id of the category in the table row.
This calls a partial called _toggle_active.html.erb and updates the appropriate <td> with the new html:
<% status = #category.is_active? ? 'Active' : 'Inactive' %>
<button class="button_<%= status %>"><%= link_to status, toggle_active_path(:id => #category.id), :method => :post, :remote => true %></button>
Now all you need is a route to access the AJAX link:
routes.rb:
post 'toggle_active' => 'categories#toggle_is_active'
Here is a working example you can clone on github. It has the stylesheets to get the look above. I think you can extrapolate this for almost any situation:
https://github.com/Beartech/category_boxes
Let's consider what's going on here:
def enable
Category.update(params[:category_ids], params[:category_ids].map{ |e| {is_active: true} })
redirect_to categories_path
end
Can you post what params[:category_ids] looks like here? the map here doesn't quite make sense. Also, what is the data type of is_active in the database?

DB Query in Ruby on Rails

I am trying to perform a database search in an application, however, I have been unable to get the search to work properly.
In the index page I have the option to search or display all items in the database, however the return all always seems to be called, instead of the search. If someone searches, I would like to only display the searched for item when the search is completed.
I am, however, running into some issues.
articles_controller.rb:
class ArticlesController < ApplicationController
def index
if params[:id]
fun = Article.find_by(title: params[:id].search)
else
#articles = Article.all
end
end
def show
#article = Article.find(params[:search])
end
def new
#article = Article.new
end
def edit
#article = Article.find(params[:id])
end
def create
#article = Article.new(params.require(:article).permit(:title, :text))
if #article.save
redirect_to #article
else
render 'new'
end
end
def update
#article = Article.find(params[:id])
if #article.update(article_params)
redirect_to #article
else
render 'edit'
end
end
def destroy
#article = Article.find(params[:id])
#article.destroy
redirect_to articles_path
end
private
def article_params
params.require(:article).permit(:title, :text)
end
end
article.rb:
class Article < ActiveRecord::Base
validates :title, presence: true,
length: { minimum: 5 }
def self.search(search)
if :search
Article.where('tite LIKE ?', "%#{search}%")
else
Article.all
end
end
end
index.html.erb:
<h1>Listing articles</h1>
<%= link_to 'New article', new_article_path %>
<table>
<tr>
<th>Title</th>
<th>Text</th>
<th colspan="3"></th>
</tr>
<% #articles.each do |article| %>
<tr>
<td><%= article.title %></td>
<td><%= article.text %></td>
<td><%= link_to 'Show', article_path(article) %></td>
<td><%= link_to 'Edit', edit_article_path(article) %></td>
<td><%= link_to 'Destroy', article_path(article),
method: :delete,
data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
<%= form_tag articles_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :title => nil %>
</p>
<% end %>
</table>
Backend DB:
Started GET "/articles?search=asdfa&commit=Search&utf8=%E2%9C%93" for ::1 at 2016-03-14 15:01:12 -0400
Processing by ArticlesController#index as HTML
Parameters: {"search"=>"asdfa", "commit"=>"Search", "utf8"=>"✓"}
Article Load (0.1ms) SELECT "articles".* FROM "articles"
Rendered articles/index.html.erb within layouts/application (1.4ms)
Completed 200 OK in 19ms (Views: 18.6ms | ActiveRecord: 0.1ms)
The latest error/incorrect call is:
Started GET "/assets/application.self-3b8dabdc891efe46b9a144b400ad69e37d7e5876bdc39dee783419a69d7ca819.js?body=1" for ::1 at 2016-03-14 15:39:25 -0400
Started GET "/articles?search=asdfa&commit=Search&utf8=%E2%9C%93" for ::1 at 2016-03-14 15:39:40 -0400
Processing by ArticlesController#index as HTML
Parameters: {"search"=>"asdfa", "commit"=>"Search", "utf8"=>"✓"}
Article Load (0.1ms) SELECT "articles".* FROM "articles"
Rendered articles/index.html.erb within layouts/application (1.3ms)
Completed 200 OK in 18ms (Views: 17.2ms | ActiveRecord: 0.1ms)
What exactly am I doing wrong? How can I fix/make this work?
You've defined search method in your model, but you are not using in it in your controller:
def index
#articles = Article.search params[:search]
end
In your model, you have some logic errors (symbol :search instead of search variable, tite instead of title ):
def self.search search
search.present? ? where('title LIKE ?', "%#{search}%") : all
end
In your controller you have:
def index
if params[:id]
fun = Article.find_by(title: params[:id].search)
else
#articles = Article.all
end
end
but you are definitely not passing any id to the controller via the form.
For example, you can change the condition to:
if params[:search]
and then find by:
Article.find_by(title: params[:search])

I am getting a "We're sorry, but something went wrong." error while trying to access a page from the browser window?

this is my controller :-
class MessagesController < ApplicationController
def new
#messages = Message.all
end
def show
#messages = Message.all
end
end
This is new.html.erb :-
<%= #messages.name %>, <%= #messages.email %>
this is my show.html.erb :-
<h1>Inbox</h1>
<table width="500" height="20" border="0" class="borderTable inlineTable" >
<tr>
<th>FROM</th>
<th>SUBJECT</th>
<th>RECEIVED AT</th>
<th></th>
<th></th>
<th></th>
</tr>
<% #messages.each do |m| %>
<% if m.to == get_user %>
<% if m.have_read == 0 %>
<font color="red">
<tr>
<td><font color="blue"><%= link_to m.from, "#" %></font></td>
<td><font color="blue"><%= link_to m.subject, "#" %></font></td>
<td><font color="blue"><%= link_to m.created_at, "#" %></font></td>
</tr>
<% else %>
<tr>
<td><%=link_to m.from , "#"%></td>
<td><%=link_to m.subject , "#"%></td>
<td><%=link_to m.created_at, "#" %></td>
</tr>
<% end %>
<% end %>
<% end %>
</table>
<br>
I when i try to access the new page by typing in "http://localhost:3000/messages/new" I get the correct page .
But when i try to access "http://localhost:3000/messages/show" I receive an error.
I have made the show.html.erb manually . Am i supposed to specify something in the routes.rb file , for it to work correctly?
this is my routes.rf file :-
Rails.application.routes.draw do
get 'messages/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 'newmain' => 'users#newmain'
get 'login' => 'sessions#new'
post 'login' => 'sessions#create'
delete 'logout' => 'sessions#destroy'
resources :users
end
Yes, you're supposed to either set messages as a resource or specify the route:
Specifying route:
get 'messages/show' => 'messages#show'
Creating resource:
resources :messages
I suggest the first one, and I suggest you either always write the => (I do) or never do, as it can become pretty confusing, pretty quickly.

Rails: Controllers update action failing to update mysql database

I'm fairly new to rails so please bear with me.
I have a resource :examen with a has_one relation to a resource :aanwezigheidslijst.
In the aanwezigheids_controller i have everything prepared for editing "aanwezigheidslijst".
Now the problem I'm having is when editing (specificly showing whether or not a student was attending or not by checking a checkbox) each "aanwezigheidslijst" is when i submit the form it renders to 'index' (just like i want) but apparently no changes have been made to the mysql database.
There are no errors that pop up and the lay-out is like i want it, it's just the checkbox that represents the boolean "aanwezig" that isn't updated when i submit it.
The connection with the mysql database works fine with other parts of the app.
any solutions are very much appreciated.
EDIT
as proposed i took a look at the log file. I figure the Unpermitted parameters have something to do with it? can anyone clarify?
Log File:
Started PATCH "/aanwezigheidslijst/2/edit" for 127.0.0.1 at 2015-02-21 16:12:14 +0100
Processing by AanwezigheidslijstController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"uxgvXaOPs66wtYBntTr907RN4yfC0vLTfresXPURBow=", "aanwezigheidslijst"=>{"1"=>{"student"=>"Tom Nys", "aanwezig"=>"1"}, "2"=>{"student"=>"Jan de Roeck", "aanwezig"=>"1"}, "3"=>{"student"=>"Nick van Heertum", "aanwezig"=>"0"}}, "commit"=>"Save Aanwezigheidslijst", "id"=>"2"}
[1m[35mAanwezigheidslijst Load (0.0ms)[0m SELECT `aanwezigheidslijsts`.* FROM `aanwezigheidslijsts` WHERE `aanwezigheidslijsts`.`id` = 2 LIMIT 1
Unpermitted parameters: 1, 2, 3
[1m[36m (1.0ms)[0m [1mBEGIN[0m
[1m[35m (0.0ms)[0m COMMIT
Redirected to http://localhost:3000/aanwezigheidslijst/index
Completed 302 Found in 8ms (ActiveRecord: 1.0ms)
aanwezigheidslijst migration:
class CreateAanwezigheidslijsts < ActiveRecord::Migration
def change
create_table :aanwezigheidslijsts do |t|
t.string :student
t.boolean :aanwezig
t.timestamps
end
end
end
aanwezigheids_controller.rb:
class AanwezigheidslijstController < ApplicationController
def index
#aanwezigheidslijst = Aanwezigheidslijst.all
#examen = Examen.all
end
def edit
#aanwezigheidslijst = Aanwezigheidslijst.where(:examen_id => params[:id]).all
end
def update
#aanwezigheidslijst = Aanwezigheidslijst.find(params[:id])
if #aanwezigheidslijst.update(aanwezig_params)
redirect_to aanwezigheidslijst_index_path
else
render 'edit'
end
end
private
def aanwezig_params
params.require(:aanwezigheidslijst).permit(:student, :aanwezig)
end
end
edit.html.erb:
<div class="tblAanwezig">
<div class="col-xs-6 col-sm-3">
<table class="table table-bordered table-condensed" style="max-width: 300px;">
<thead>
<tr>
<th scope="col">Student</th>
<th scope="col">Aanwezig</th>
</tr>
</thead>
<%= form_tag edit_aanwezigheidslijst_url, :id => 'al_form', method: :patch do %>
<% #aanwezigheidslijst.each do |aanwezigheidslijst| %>
<%= fields_for "aanwezigheidslijst[]", aanwezigheidslijst do |al| %>
<tbody>
<tr>
<td> <%= al.text_field :student %></td>
<td><%= al.check_box :aanwezig %></td>
</tr>
</tbody>
<% end %>
<% end %>
</table>
<%= submit_tag "Save Aanwezigheidslijst" %>
<% end %>
</div>
</div>
routes.rb
Rails.application.routes.draw do
get 'aanwezigheidslijst/index'
patch 'aanwezigheidslijst/:id/edit' => 'aanwezigheidslijst#update'
get 'examen/index'
get 'comments/new'
post 'comments/new'
get 'comments/update'
get 'comments/create'
get 'application/application'
resources :comments
resources :aanwezigheidslijst
root 'comments#index'
end

Ruby on Rails save a record on database based on post data

I've been playing around with this for the past 6 hours and I really can't solve it. I'm new to ruby on rails. I have a products and I have added a purchases model. now I want a 'buy' key next to each product to add it to my purchases database. This is my Purchases controller:
class PurchasesController < ApplicationController
def new
end
def update
end
def create
#purchase = Purchase.new(purchase_params)
if Purchase.save
redirect_to products_path notice: 'Product bough'
else
redirect_to products_path notice: 'Error!!!'
end
end
private
def purchase_params
params.require(:product).permit(:amount,:product_id)
end
And the buy button:
<td><%= link_to 'Buy',purchases_path(product.attributes), method: :post %></td>
And that's within <% #products.each do |product %>. Now I really wanna know how to send product_id and then save it in my purchases database. I keep getting all sorts of errors!
Like parameter not found: product to undefined methodpermit' for "8":String8 is the product id andmethod save is undefined ...`. I think I really don't know what I'm doing here! A little help or tutorial on how to manually save data to database will be appreciated. (by manually I mean entering which posted field to saved for which col)
You should do #purchase.save, not Purchase.save
Something like this should be your view.
<% #products.each do |product| %>
<td><%= product.amount %><td>
<td><%= form_for #product, url: {action: "create"}, html: {method: "post"} do |f| %>
<%= f.hidden_field_tag :id,product.id%>
<%= f.hidden_field_tag :amount,product.amount%>
<%= f.submit "Create" %>
<% end %></td>
<% end %>
Your controller should look something like this:
def create
#purchase = Purchase.new(purchase_params)
if #purchase.save
redirect_to products_path notice: 'Product bough'
else
redirect_to products_path notice: 'Error!!!'
end
end
def purchase_params
params.require(:product).permit(:amount,:id)
end
I am not sure why you want to not use the form. Why is that? Anyway here is a solution.
<td><%= link_to 'Buy',purchases_path(amount: product.amount,id: product.id), method: :post %></td>
This should work. Try this.