Incrementing Values in Rails 3 using link_to - ruby-on-rails

i want to update viewcount value in Posts table when user click the "like" link in post........
model
class Post < ActiveRecord::Base
belongs_to :user
has_many :answers
attr_accessible :acceptedanswerid, :body, :userid, :tag, :title, :viewcount, :vote, :anscount
validates_presence_of :title ,:body ,:tag
scope :unanswered, where(:anscount => 0)
scope :byvote, where(:vote=>maximum("vote"))
end
controller
post_controller.rb
class PostController < ApplicationController
def index
#post=Post.new
#answer=Answer.new
#anscomment=Anscomment.new
#posts=(Post.all).reverse
#posts1=Post.all(:limit => 5 ,:order => "id desc")
#unanswered = Post.unanswered
#byvote=Post.byvote
#fid=params[:fid]
session[:flag]=nil
fid=params[:fid]
session[:flag]=fid
end
#def new
# #post=Post.new
# end
def create
# #post=Post.new(params[:post])
#post=Post.new(params[:post])
respond_to do |format|
if #post.save
#if (session[:flag!=nil])
#session[:flag]=1
#end
format.html { redirect_to :controller=>"post" ,:action=>"index" }
format.json { render json: #post, status: :created, location: #post }
#redirect_to :controller=>"post" ,:action=>"index"
else
#session[:flag]=3
format.html { redirect_to :controller=>"home" ,:action=>"index" }
format.json { render json: #post, status: :created, location: #post }
#redirect_to :controller=>"post" ,:action=>"index"
end
end
end
def show
id=params[:id]
#post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #post }
end
end
def vote
vcount = User.find(params[:id])
vcount.update_attribute(:viewcount, vcount.viewcount + 4)
end
end
view
views/post/show.html.erb
<table align=center width="60%" bordercolor="black" >
<tr>
<td align="center">
<h2>
<%=#post.title%>
</h2>
</td>
</tr>
<tr>
<td align="center" width="60">
<h3><%=#post.body%></h3>
</td>
</tr>
<tr>
<td align="center">
This Post comes under:<%=#post.tag%>
</td>
</tr>
<tr >
<td align="right">
<%id=#post.userid %>
<%if id==nil %>
<%id='15'%>
<%end%>
<%#user=User.find(id)%>
posted by:<%=#user.fullname%> <p>on <%=#post.created_at%></p>
<%id=nil%>
<h1 align="left"><%=#post.answers.count%></h1>
<!--<%Post.increment_counter(:viewcount,#post.id) %>-->
<%= link_to "like", {:controller => "post", :action => "vote", :id => #post.id } %>
</td>
</tr>
</table>
when i click the "like" the like link i am getting an error like-----Couldn't find Post with id=vote
*application trace: *
app/controllers/post_controller.rb:42:in `show'
plz help me finding the error.......

i think it happens because in your routes.rb file /post/:id is before :controller/:action:/:id, so u have to create named route for this action.
resources :posts do
get 'vote', on: member
end
and the use path helper vote_post_path(post)
http://guides.rubyonrails.org/routing.html

Related

Rails Export multiple tables to csv

Hi I have a simple rails application that has two models Equipment_Types & Tasks
Each equipment type has many tasks. When I export to csv file I would like to export the name of the equipment type, the task name and the associated schedule. Basically every thing that is displayed on equipment_type/show.html.erb
<p id="notice"><%= notice %></p>
<div class="row">
<table class="table table-bordered">
<thead>
<tr>
<th class="align-middle" rowspan="2">Equipment</th>
<th class="align-middle" rowspan="2">Task</th>
<th class="text-center" colspan="4">Frequency</th>
</tr>
<tr>
<th class="text-center">M</th>
<th class="text-center">Q</th>
<th class="text-center">B</th>
<th class="text-center">A</th>
</tr>
</thead>
<tbody>
<tr>
<% if #taskcount > 3 %>
<td class="text-center bottomtotop" rowspan="0"><%= link_to #equipment_type.name, edit_equipment_type_path(#equipment_type) %></td>
<% else %>
<td class="text-center" rowspan="0"><%= link_to #equipment_type.name, edit_equipment_type_path(#equipment_type) %></td>
<% end %>
</tr>
<% #equip_tasks.each do |task| %>
<tr>
<td><%= link_to task.name, task %></td>
<td class="text-center"><%= if task.monthly then 'x' else ' ' end %></td>
<td class="text-center"><%= if task.quarterly then 'x' else ' ' end %></td>
<td class="text-center"><%= if task.sixmonthly then 'x' else ' ' end %></td>
<td class="text-center"><%= if task.annually then 'x' else ' ' end %></td>
</tr>
<% end %>
<div class="collapse" id="collapsenewline">
</div>
</tbody>
</table>
</div>
<div class="row">
<div class="col-sm">
<%= link_to 'Add Task', new_task_path(#equipment_type), class: 'btn btn-dark' %>
</div>
<div class="col-sm">
<%= link_to 'Back', equipment_types_path, class: 'btn btn-dark' %>
</div>
<div class="col-sm">
<button class="btn btn-dark" type="button" data-toggle="collapse" data-target="#collapsedownload" aria-expanded="false" aria-controls="collapseExample">
Download
</button>
</div>
</div>
<div class="row">
<div class="col-sm">
</div>
<div class="col-sm">
</div>
<div class="col-sm">
<div class="collapse" id="collapsedownload">
<div class="card card-body">
<h3>Download File</h3>
<%= link_to "csv", equipment_types_path(format: "csv"), class: 'btn btn-dark' %>
<br>
<%= link_to "pdf", equipment_types_path(format: "pdf"), class: 'btn btn-dark' %>
<br>
<%= link_to "word", equipment_types_path(format: "word"), class: 'btn btn-dark' %>
</div>
</div>
</div>
</div>
equipment_type Model
class EquipmentType < ApplicationRecord
has_many :tasks
accepts_nested_attributes_for :tasks
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
EquipmentType.create! row.to_hash
end
end
def self.to_csv
CSV.generate do |csv|
csv << column_names
all.each do |equipmenttype|
csv << equipmenttype.attributes.values_at(*column_names)
end
end
end
end
equipment_types Controller
class EquipmentTypesController < ApplicationController
before_action :set_equipment_type, only: [:show, :edit, :update, :destroy]
before_action :set_task, only: [:show]
# GET /equipment_types
# GET /equipment_types.json
def index
#equipment_types = EquipmentType.all
respond_to do |format|
format.html
format.csv { send_data #equipment_types.to_csv }
end
end
# GET /equipment_types/1
# GET /equipment_types/1.json
def show
#equipment_type = EquipmentType.find_by(id: params[:id])
#tasks = Task.all
#equip_tasks = #equipment_type.tasks.all
#taskcount = #equip_tasks.count
respond_to do |format|
format.html
format.csv { send_data text: #equip_tasks.to_csv }
end
end
# GET /equipment_types/new
def new
#equipment_type = EquipmentType.new
end
# GET /equipment_types/1/edit
def edit
end
# POST /equipment_types
# POST /equipment_types.json
def create
#equipment_type = EquipmentType.new(equipment_type_params)
respond_to do |format|
if #equipment_type.save
format.html { redirect_to #equipment_type, notice: 'Equipment type was successfully created.' }
format.json { render :show, status: :created, location: #equipment_type }
else
format.html { render :new }
format.json { render json: #equipment_type.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /equipment_types/1
# PATCH/PUT /equipment_types/1.json
def update
respond_to do |format|
if #equipment_type.update(equipment_type_params)
format.html { redirect_to #equipment_type, notice: 'Equipment type was successfully updated.' }
format.json { render :show, status: :ok, location: #equipment_type }
else
format.html { render :edit }
format.json { render json: #equipment_type.errors, status: :unprocessable_entity }
end
end
end
def import
EquipmentType.import(params[:file])
redirect_to equipment_type_path, notice: "Equipment Type Added Successfully"
end
# DELETE /equipment_types/1
# DELETE /equipment_types/1.json
def destroy
#equipment_type.destroy
respond_to do |format|
format.html { redirect_to equipment_types_url, notice: 'Equipment type was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_equipment_type
#equipment_type = EquipmentType.find(params[:id])
end
def set_task
#task = Task.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def equipment_type_params
params.require(:equipment_type).permit(:name, task: [])
end
end
Task Model
class Task < ApplicationRecord
belongs_to :equipment_type
end
Tasks Controller
class TasksController < ApplicationController
before_action :set_task, only: [:show, :edit, :update, :destroy]
# GET /tasks
# GET /tasks.json
def index
#tasks = Task.all
end
# GET /tasks/1
# GET /tasks/1.json
def show
end
# GET /tasks/new
def new
#task = Task.new
end
# GET /tasks/1/edit
def edit
end
# POST /tasks
# POST /tasks.json
def create
#task = Task.new(task_params)
respond_to do |format|
if #task.save
format.html { redirect_to #task, notice: 'Task was successfully created.' }
format.json { render :show, status: :created, location: #task }
else
format.html { render :new }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /tasks/1
# PATCH/PUT /tasks/1.json
def update
respond_to do |format|
if #task.update(task_params)
format.html { redirect_to #task, notice: 'Task was successfully updated.' }
format.json { render :show, status: :ok, location: #task }
else
format.html { render :edit }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
# DELETE /tasks/1
# DELETE /tasks/1.json
def destroy
#task.destroy
respond_to do |format|
format.html { redirect_to tasks_url, notice: 'Task was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_task
#task = Task.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def task_params
params.require(:task).permit(:name, :monthly, :quarterly, :sixmonthly, :annually, :equipment_type_id)
end
end
This should get you started:
You merely need to just append the attributes to the array.
Instead of,
csv << equipmenttype.attributes.values_at(*column_names)
Drop in this (or similar) (note: this is resource-intensive so you'll want to trim it down especially if you have lots of tasks)
def csv_attributes
{
tasks: self.tasks.all.map(&:attributes).map(&:values),
id: self.id
}
end
and then
csv << equipmenttype.csv_attributes

How to Update a model while creating another model using one form in rails

Pls i need help here.
i have 2 models:- due_job and outgoing_job
due_job has_many outgoing_jobs
outgoing_job belongs_to due_job.
Im trying to update a user's outgoing_job as done while at the same time create a due_job for another user.
My models:
class DueJob < ActiveRecord::Base
belongs_to :user
has_many :outgoing_jobs
accepts_nested_attributes_for :outgoing_jobs
end
class OutgoingJob < ActiveRecord::Base
belongs_to :user
belongs_to :outgoing_jobs
accepts_nested_attributes_for :outgoing_jobs
end
Controllers:
class OutgoingJobsController < ApplicationController
def index
#outgoing_job = OutgoingJob.new
#outgoing_jobs = OutgoingJob.all
end
def new
#outgoing_job = OutgoingJob.new
end
def create
#outgoing_job = OutgoingJob.new(outgoing_job_params)
respond_to do |format|
if #outgoing_job.save
flash.now[:success] = "saved"
format.html {redirect_to current_user}
format.json {render json: #outgoing_job, status: :created, location: #outgoing_job}
else
flash[:danger] = "not saved"
format.html {redirect_to root_path}
format.json {render json: #outgoing_job.errors, status: :unprocessable_entity }
end
end
end
def show
#outgoing_job = OutgoingJob.find(params[:id])
end
def update
#outgoing_job = OutgoingJob.find(params[:id])
respond_to do |format|
if #outgoing_job.update(outgoing_job_params)
format.html { redirect_to '/users/outgoing_job_dashboard', notice: 'job updated' }
format.json {render action: 'show', status: :ok, location: #outgoing_job }
else
format.html { render action: 'edit'}
format.json { render json: #outgoing_job.errors, status: :unprocessable_entity}
end
end
end
def destroy
#outgoing_job.destroy
respond_to do |format|
format.html {redirect_to current_user}
format.json { head :no_content}
end
end
private
def outgoing_job_params
params.require(:outgoing_job).permit(:outgoing_job_value,
:sent,
:confirmed,
:done,
:due_job_id,
:user_id )
end
end
the controller for due_jobs is essentially same.
However, when i do this in my view:
<% OutgoingJob.all.each do |od| %>
<table class="table table-striped table-responsive">
<thead>
<tr>
<th>ID</th>
<th>Done By</th>
<th>Done for</th>
<th>Beneficiary</th>
<th>Amount proposed</th>
<th>Amount to paid</th>
<th>Create due job</th>
<th>Actions</th>
</tr>
</thead>
<% if (od.confirmed == true) && (od.done== false) %>
<tbody>
<tr>
<td><%= od.id %></td>
<td><%= od.user.first_name %> <%= od.user.last_name %></td>
<td><%= od.due_job.user.first_name %> <%= od.due_job.user.last_name %></td>
<td><%= od.due_job.user.user_detail %></td>
<td>$ <%= number_with_delimiter(od.outgoing_job_value, delimiter: ',') %> </td>
<td> <%= --- %> </td>
<td>
<%= simple_form_for (DueJob.new) do |u| %>
<%= u.hidden_field :due_job_value, value: od.outgoing_job_value %>
<%= u.hidden_field :user_id, value: od.user.id %>
<%= u.fields_for od do |f| %>
<%= f.hidden_field :done, value: true %>
<%end%>
<%= u.submit "create", class: "btn btn-success" %>
<%end%>
</td>
<td><%= link_to "View", od %></td>
</tr>
</tbody>
<%end%>
</table>
.....
Using nested form i am able to create a new record for DueJob tho, but it doesnt update outgoing_job. What am i missing pls?
I suggest you make use of ActiveRecord callbacks to relegate some of the code to your models (I doubt that trying to do everything from one view is the way to go).
In your model for DueJob add something like:
class DueJob < ActiveRecord::Base
# Register a callback to execute every time you create a new DueJob
after_create :update_done_flag_on_outgoing_job
# ... and add some code for that callback.
def update_done_flag_on_outgoing_job
outgoing_job.update_attribute :done, true
end
Just from reading your source code, I was struggling to understand how you identify the connections between the newly created DueJob and the specific OutgoingJob record that you want to update. Like #coreyward pointed out, it would be helpful if you could present your code a bit more neatly. If you can't use my example snippet as is, I guess you can always adapt the update_done_flag_on_outgoing_job method to your needs.
Hope you find that helpful.

Nested form(cocoon gem) inside a table in rails

I'm busy with a invoicing application and i'm trying to put a nested form from the cocoon gem inside a <tbody></tbody>. The nested form is working perfectly but it doesn't show up in the <tbody></tbody> but at some random place above the table head. I think it's because you can't have <div class=nested-fields></div> inside the table body but i'm not sure how to do it differently.
i have this in my invoices/_form.html.erb :
<%= form_for #invoice do |f| %>
<% if #invoice.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#invoice.errors.count, "error") %> prohibited this invoice from being saved:</h2>
<ul>
<% #invoice.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="row">
<div class="col-sm-12">
<table class="table table-striped">
<thead>
<tr>
<th class="hidden-480"> Hoeveelheid </th>
<th class="hidden-480"> Beschrijving </th>
<th class="hidden-480"> Bedrag </th>
<th class="hidden-480"> Totaal </th>
<th class="hidden-480"> Btw(%) </th>
</tr>
</thead>
<tbody>
<%= f.fields_for :products do |product| %>
<%= render 'product_fields', f: product %>
<%= link_to_add_association 'Item toevoegen', f, :products, class: 'btn btn-primary btn-success' %>
<% end %>
</tbody>
</table>
</div>
</div>
<% end %>
invoices/_product_fields.html.erb
<div class="nested-fields">
<tr>
<td> <%= f.text_field :quantity %> </td>
<td> <%= f.text_area :description %> </td>
<td> <%= f.number_field :unitprice %> </td>
<td> €200 </td>
<td> <%= f.select(:btw, [[' 21%', 21, title: '21%'],[' 6%', 6, title: '6%'], [' 0%', 0, title: '0%']]) %> </td>
</tr>
<%= link_to_remove_association 'x', f, class: 'btn btn-primary btn-danger' %>
</div>
Invoice.rb - model
class Invoice < ActiveRecord::Base
has_one :company
has_one :customer
has_many :products
accepts_nested_attributes_for :customer, reject_if: :all_blank, allow_destroy: true
accepts_nested_attributes_for :products, reject_if: :all_blank, allow_destroy: true
validates :number, :currency, :date, :duedate, :btwtotal, :subtotal, :total, presence: true
end
Product.rb - model
class Product < ActiveRecord::Base
belongs_to :invoice
end
Invoices_controller.rb
class InvoicesController < ApplicationController
before_action :set_invoice, only: [:show, :edit, :update, :destroy]
# GET /invoices
# GET /invoices.json
def index
#invoices = Invoice.all
end
# GET /invoices/1
# GET /invoices/1.json
def show
end
# GET /invoices/new
def new
#invoice = Invoice.new
#invoice.products.build
end
# GET /invoices/1/edit
def edit
end
# POST /invoices
# POST /invoices.json
def create
#invoice = Invoice.new(invoice_params)
respond_to do |format|
if #invoice.save
format.html { redirect_to #invoice, notice: 'Invoice was successfully created.' }
format.json { render :show, status: :created, location: #invoice }
else
format.html { render :new }
format.json { render json: #invoice.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /invoices/1
# PATCH/PUT /invoices/1.json
def update
respond_to do |format|
if #invoice.update(invoice_params)
format.html { redirect_to #invoice, notice: 'Invoice was successfully updated.' }
format.json { render :show, status: :ok, location: #invoice }
else
format.html { render :edit }
format.json { render json: #invoice.errors, status: :unprocessable_entity }
end
end
end
# DELETE /invoices/1
# DELETE /invoices/1.json
def destroy
#invoice.destroy
respond_to do |format|
format.html { redirect_to invoices_url, notice: 'Invoice was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_invoice
#invoice = Invoice.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def invoice_params
params.require(:invoice).permit(:number, :currency, :date, :duedate, :btwtotal,
:subtotal, :total, :footer, customers_attributes: [:id, :company_name, :address_line_1, :zip_code, :_destroy],
companies_attributes: [:id, :btw_number, :iban_number, :kvk_number, :company_name, :_destroy],
products_attributes: [:id, :quantity, :description, :unitprice, :btw, :total])
end
end
Any idea what's going on? Help would be much appreciated!
You can simply use built in methods provided by cocoon gem for link_to_add_association,
reference:
https://github.com/nathanvda/cocoon#link_to_add_association
<%= link_to_add_association 'Item toevoegen', f, :products,:"data-association-insertion-node" => "tbody#{id of tbody encapsulating your fields_for}",:"data-association-insertion-method" => "append", class: 'btn btn-primary btn-success' %>
P.S this is my first answer in stackoverflow, so I apologize in advance if I wasn't clear enough.
You can refer to Control the Insertion Behaviour section of cocoon gem for more reference to insert nested fields.
For example,
$(document).ready(function() {
$("#owner a.add_fields").
data("association-insertion-method", 'append').
data("association-insertion-traversal", 'closest').
data("association-insertion-node", '#parent_table');
});

Rails routing error: No route matches [DELETE]

I'm a ruby on rails noob having some trouble deleting a resource with a form_for.
I'm trying to create a wish-list for products where users can add multiple instances of the same product to their list. Rather than create a unique data-base entry for each product on the list (regardless of whether the same product is already on the list), I've included a counter column, 'row,' which increases as the user adds multiples of the same product to his or her wish list. By the same logic, I want the delete action to first decrease this counter until it reaches 0, and then remove the item from the data-base.
Here's what I've got:
The error message:
No route matches [DELETE] "/wish"
Routes
Routes match in priority from top to bottom
wishes_path GET /wishes(.:format) wishes#index
POST /wishes(.:format) wishes#create
new_wish_path GET /wishes/new(.:format) wishes#new
edit_wish_path GET /wishes/:id/edit(.:format) wishes#edit
wish_path GET /wishes/:id(.:format) wishes#show
PATCH /wishes/:id(.:format) wishes#update
PUT /wishes/:id(.:format) wishes#update
DELETE /wishes/:id(.:format) wishes#destroy
wishes/index.html.erb
<div class="wishes_body">
<h2>Your Wish-List</h2>
<table>
<thead>
<tr>
<th class="field-label col-md-2 active">
<label>Name</label>
</th>
<th class="col-md-3">Description</th>
<th class="col-md-1">Amount</th>
<th class="col-md-1">Number</th>
<th class="col-md-2">Total</th>
<th colspan="3" class="col-md-3">Remove</th>
</tr>
</thead>
<tbody>
<% #wishes.all.each do |w| %>
<%= render partial: 'wish', object: w %>
<% end %>
</tbody>
</table>
</div>
_wish.html.erb
<tr>
<td class="field-label col-md-2 active">
<label><%= wish.product.name %></label>
</td>
<td class="col-md-3"><%= wish.product.description %></td>
<td class="col-md-1"><%= '%.2f' % (wish.product.amount/100.00) %></td>
<td class="col-md-1"><%= wish.total %></td>
<td class="col-md-2"><%= '%.2f' % ((wish.product.amount/100.00) * wish.total) %></td>
<%= form for(wish_path(wish), :html => { method: 'delete' }) do %>
<td><%= f.label(:i, "How many:") %></td>
<td><%= f.number_field(:i) %></td>
<td><%= f.submit :value => "Remove" %></td>
<% end %>
</tr>
controllers/wishes.controller.rb
class WishesController < ApplicationController
def index
#wishes = Wish.where("user_id = ?", "#{current_user.id}")
end
def show
#user = current_user
#products = #user.wish_list.products.order("created_at DESC")
end
def create
#product = Product.find(params[:product_id])
if Wish.where(user_id: "#{current_user.id}", product_id: "#{#product.id}").exists?
#wish = Wish.where(user_id: "#{current_user.id}", product_id: "#{#product.id}").first
#wish.total += 1
else
#wish = #product.wishes.new
#wish.user = current_user
#wish.total = 1
end
respond_to do |format|
if #wish.save
format.html { redirect_to action: "index", notice: 'You have added <%= #wish.product %> to your wish list.' }
format.json { render :index, status: :created }
else
format.html { redirect_to #product, alert: 'Wish was not created succesfully.' }
format.json { render json: #wish.errors, status: :unprocessable_entity }
end
end
end
def destroy
case i = params[:i]
when #wish.total > i
#wish.total -= i
respond_to do |format|
format.html { redirect_to action: 'index', notice: 'You removed the item from your wish-list.' }
format.json { head :no_content }
end
when #wish.total == i
#wish.destroy
respond_to do |format|
format.html { redirect_to action: 'index', notice: 'You removed the item from your wish-list.' }
format.json { head :no_content }
end
else
format.html { redirect_to action: 'index', alert: 'You cannot remove more items than you have on your list.' }
format.json { head :no_content }
end
end
end
config.routes.rb
Rails.application.routes.draw do
root 'static_pages#index'
get 'static_pages/about'
get 'static_pages/contact'
get 'static_pages/landing_page'
post 'static_pages/thank_you'
resources :orders, only: [:index, :show, :new, :create]
resources :users
devise_for :users, :controllers => { :registrations => "my_devise/registrations" },
:path => '', :path_names => {:sign_in => 'login', :sign_out => 'logout', :sign_up => 'register'}
resources :wishes
resources :products do
resources :comments
end
resources :payments
end
You should implement this using form_tag instead of form_for, because you're not going to use #wish resource in your form:
<%= form_tag wish_url(wish), method: :delete do %>
etc.

Strange Routing error in rails 3.2

I am implementing an application in which i want to change the settings of the application.
While doing so I am getting an error
no routes matches {:action=>"show", :controller=>"settings", format=>"nil"}
while clicking on the open new settings tab.
my index.html is as follows:-
<h1>Listing settings</h1>
<table class="table table-striped table-bordered">
<tr>
<th>ID</th>
<th>Name</th>
<th>Value</th>
<th>Description</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<% #settings.each do |c| %>
<tr>
<td><%= c.id %> </td>
<td><%= c.name %> </td>
<td><%= c.value %> </td>
<td><%= c.description %> </td>
<td><%= link_to 'Edit', {:action => 'edit', :id => c.id} %> </td>
<td><%= link_to 'Delete', {:action => 'delete', :id => c.id},
:data => { :confirm => "Are you sure you want to delete this value?" } %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New Setting', {:action => 'new'} %>
My settings controller is as follows:-
class SettingsController < ApplicationController
# GET /setting
# GET /setting.json
def index
#settings = Setting.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #settings }
end
end
# GET /setting/1
# GET /setting/1.json
def show
#setting = Setting.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #setting }
end
end
# GET /setting/new
# GET /setting/new.json
def new
#setting = Setting.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #setting }
end
end
# GET /setting/1/edit
def edit
#setting = Setting.find(params[:id])
end
# POST /setting
# POST /setting.json
def create
#setting = Setting.new(params[:setting])
respond_to do |format|
if #setting.save
format.html { redirect_to #setting, notice: 'Setting was successfully created.' }
format.json { render json: #setting, status: :created, location: #setting }
else
format.html { render action: "new" }
format.json { render json: #setting.errors, status: :unprocessable_entity }
end
end
end
# PUT /setting/1
# PUT /setting/1.json
def update
#setting = Setting.find(params[:id])
respond_to do |format|
if #setting.update_attributes(params[:setting])
format.html { redirect_to #setting, notice: 'Setting was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #setting.errors, status: :unprocessable_entity }
end
end
end
# DELETE /setting/1
# DELETE /setting/1.json
def delete
#setting = Setting.find(params[:id])
#setting.deleted = 1
#setting.save
respond_to do |format|
format.html { redirect_to settings_url }
format.json { render :json => { :success => true } }
end
end
end
My new.html is as follows:-
<h1>New settings</h1>
<%= form_for #setting do |f| %>
<% if #setting.errors.any? %>
<div id="errorExplanation">
<h2><%= pluralize(#setting.errors.count, "error") %> prohibited this setting from being saved:</h2>
<ul>
<% #setting.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
Id: <%= f.text_field :id %><br>
Name: <%= f.text_field :name %><br>
Values: <%= f.text_field :value %><br>
Description: <%= f.text_field :description %><br>
<% end %>
<%= link_to 'Back', settings_path %>
My routes.rb is as follows:-
Lms::Application.routes.draw do
resources :books do
member do
post 'add'
post 'remove'
end
collection do
get 'add'
get 'list' => "books#index"
post 'get_books'
get 'get_books'
end
end
resources :books
resources :book_transactions
resources :book_issues
resources :book_holds
resources :categories
resources :users
resources :admins
resources :library_locations
resources :lov_values
resources :loan_fines
resources :lov_names
resources :loans_fines do
member do
post 'add'
post 'remove'
end
collection do
get 'add'
get 'list'
post 'get_loans_fines'
get 'get_loans_fines'
end
end
resources :settings do
member do
post 'add'
post 'remove'
end
collection do
get 'add'
get 'list'
post 'get_settings'
get 'get_settings'
end
end
root :to => 'books#index'
match ':controller(/:action(/:id))(.:format)'
The strange part is that when i click on new action it is going/redirecting to the show action..I am a bit confused why this is happening..
Can some one help me with this..
To check your routes you can run
rake routes
to inspect if you have the routes defined correctly. Also I would suggest to use
<%= link_to "New Setting", new_setting_pah %>
For your routes definition you are not defining the routes for other methods than add or remove.
I advise you to read this great tutorial on rails routes

Resources