Ruby on Rails custom update action - ruby-on-rails

I want to update member_id, which triggers update of :location_stock.
I have got these custom actions in
costumes_and_cost_records_controller.rb:
def rent
#costumes_and_cost_record = CostumesAndCostRecord.find(params[:costumes_and_cost_record_id])
end
def rent_method
#costumes_and_cost_record = CostumesAndCostRecord.find(params[:costumes_and_cost_record_id])
#costumes_and_cost_record.update_attributes(:member_id => params.permit(:member_id), :location_stock => true)
redirect_to #costumes_and_cost_record
end
I used simple form in view rent.html.erb:
<%= simple_form_for #costumes_and_cost_record do |f| %>
<%= f.association :member, :label => "Member", label_method: :to_s, value_method: :member_id, include_blank: true %>
<%= f.submit "Rent", :controller => :costumes_and_cost_records, :action => :rent_method, :method => :put, :member_id => :member %> <%# updates only member_id, doesnt update :location_stock %>
<%# link_to "Rent", :controller => :costumes_and_cost_records, :action => :rent_method, :method => :put, :member_id => :member_id %> <%# updates :location_stock, sets member_id = NULL %>
<% end %>
Now if I use submit button :member_id updates but controller doesn't update :location_stock.
If I use link_to :location_stock updates, but :member_id is set to NULL.
I want to update both attributes. Should I use submit button or link_to and how to fix this issue?
I set routes.rb to make both link_to and submit methods in view work:
resources :costumes_and_cost_records do
post 'show'
get 'rent'
get 'rent_method'
end
Any help is greatly appreciated.

If I understand you correctly you need to call rent_method to update member_id
Routes changes
put 'rent_method'
View changes
<%= simple_form_for #costumes_and_cost_record, method: :put, url: [#costumes_and_cost_record, :rent_method] do |f| %>
<%= f.association :member, :label => "Member", label_method: :to_s, value_method: :member_id, include_blank: true %>
<%= f.submit "Rent" %>
<% end %>
Controller
def rent_method
#costumes_and_cost_record = CostumesAndCostRecord.find(params[:costumes_and_cost_record_id])
#costumes_and_cost_record.update_attributes(:member_id => member_params[:member_id], :location_stock => true)
redirect_to #costumes_and_cost_record
end
def member_params
params.require(:costumes_and_cost_record).permit(:member_id)
end

Routes
Firstly, if you want to have member_id present, you'll probably be best using nested routes as follows:
#config/routes.rb
resources :member do.
resources :costumes_and_cost_records do
... #-> domain.com/members/2/costumes_and_cost_records/
end
end
This will give you the value required for params[:member_id] from your link:
<%= link_to "Member", member_costumes_and_cost_records_path(member_id) %>
Form
In your form, you then need to be able to define the url correctly (Rails naturally submits to the CRUD based actions, not custom ones):
<%= simple_form_for #costumes_and_cost_record, url: your_rent_method_path, method: :patch do |f| %>
This will submit to the rend_method path, or whichever custom action you wish to request.
--
I would personally keep any activity you have in the controller to a single action - this will allow you to keep all the business logic in one action, which is preferred for the MVC programming pattern

It took me 3 days but I finally fixed the problem. Ruslan Kyrychuk's answer was good, but the problem was that I didn't follow Rails naming conventions. I had foreign key: costumes_and_cost_records.member_id and primary key:member.member_id so I renamed member.member_id to member.id and that fixed the problem.

Related

Jquery UI Autocomplete for Search Form that Passes Params into Query String

I have successfully used Jquery Autocomplete for other forms on my website but this one is giving me trouble.
// Controller
class UsersController < ApplicationController
autocomplete :user, :name,
...
end
// Routes
resources :users do
get :autocomplete_name, :on => :collection
end
//View
<% form_tag users_path, method: :get do %>
<%= autocomplete_field_tag :name, params[:name], autocomplete_name_users_path, :placeholder => "Search by name" %>
<%= submit_tag "Search", :id => "submit" %>
<% end %>
The search form works but the auto complete is not showing.
Please replace with following in routes.rb file,
resources :users do
get :autocomplete_user_name, :on => :collection
end
Please refer Rails 4 autocomplete for more documentation.

Ruby on rails changes not reflecting after editing user's details

I am Rails newbie. I am creating a section that is pulling existing user's details and when the user click on edit, he can save the changes he has made. However, the changes aren't reflecting once the user saves it. Can you tell me what I am missing in here?
Here's the html/ruby form I am using:
<%= form_tag(html: {:id => 'user_profile_form'}, :url => patient_profile_path(#user), :method => :put) do %>
<%= text_field_tag(:inputFieldName, "#{#user.first_name} #{#user.last_name}", {:disabled => true}) %>
<%= submit_tag 'Save', :id=> 'saveButton' %>
<%= end %>
Here's the routes:
put :patient_profile, to: 'users#patient_profile'
post :dashboard, to: 'dashboard#index'
Here are the controller codes:
def patient_profile
if params[:user]
u = params[:user]
#user.first_name = u[:first_name] unless u[:first_name].nil? || u[:first_name].empty?
#user.last_name = u[:last_name] unless u[:last_name].nil? || u[:last_name].empty?
#user.save!
# index
render :index
end
end
It doesn't look like your form is actually updating anything since your form fields don't match your model. Try simplifying your form action:
View
<%= form_for(#user, html: {:id => 'user_profile_form'}, :url => patient_profile_path(#user), :method => :put) do |f| %>
<%= f.text_field :first_name %>
<%= f.text_field :last_name %>
<%= f.submit "Update User" %>
<%= end %>
Controller:
def patient_profile
# TODO: Handle failed validation
#user.update_attributes!(params[:user])
# index
render :index
end
end
def user_params
params.require(:user).permit(:first_name, :last_name)
end

Resource defines an update using PATCH but app wants POST in Rails 4

I'm trying to add edit functionality to my web app, and am having some trouble. The error page I get back when I try to complete an edit of my Request object indicates that it couldn't find the right route, but the same error page contains a list of routes which includes the route it's looking for. So I'm a bit flummoxed.
The "new" method is almost identical to this edit method and the pages are almost identical as well.
The error page begins No route matches [POST] "/requests/19/edit" and then, partway down the route listing, I see this:
requests_path GET /requests(.:format) requests#index
POST /requests(.:format) requests#create
new_request_path GET /requests/new(.:format) requests#new
edit_request_path GET /requests/:id/edit(.:format) requests#edit
request_path GET /requests/:id(.:format) requests#show
PATCH /requests/:id(.:format) requests#update
PUT /requests/:id(.:format) requests#update
DELETE /requests/:id(.:format) requests#destroy
So Rails seems to be generating a request_path which expects a PATCH, not a POST, right?
routes.rb
Rails.application.routes.draw do
root "pages#index"
resources :destinations
resources :users
resources :manifests
resources :requests
:
request.rb
class Request < ActiveRecord::Base
validates_presence_of :justification
validates_presence_of :required_by
belongs_to :user
belongs_to :manifest
belongs_to :network
has_many :uploaded_files
scope :sorted, lambda{ order("required_by") }
end
edit.html.rb
<% #page_title = "Update Request" %>
<%= link_to("<< Back to List", {:action => 'index'}, :class => 'back-link') %>
<div class="requests edit">
<h2>Update Request</h2>
<%= form_for :request, url: request_path(#request) do |f| %>
<%= render(:partial => "form", :locals => {:f => f}) %>
<div class="form-buttons">
<%= submit_tag("Update Request") %>
</div>
<% end %>
</div>
requests_controller.rb
def update
#request = Request.find(params[:id])
p = {'file' => params[:request][:uploaded_file], 'request_id' => #request.id}
uf = UploadedFile.create(p)
if #request.update_attributes(request_params)
flash[:notice] = "Request updatred succesfully"
redirect_to :action => 'show', :id => #request.id
else
render 'edit'
end
end
What have I missed?
Change
<%= form_for :request, url: request_path(#request) do |f| %>
to
<%= form_for :request, url: request_path(#request), method: :patch do |f| %>
in your edit.html.erb
form_for(as you are using it) sets POST as default HTTP verb. You need to alter it by setting method :patch which responds to the update action.
You can simplify it to just
<%= form_for #request do |f| %>
Check the APIdoc for more Info.

Database querying through Http in rails?

I am working on rails app , In which I have created a table Product Name:string and Number: integer.
The application should give user a form where he can search a product by his number if product exists it should give product name from database.
My search.html.erb is this.
<%= form_for #products, :url => { :action => "create" }, :html => {:class => "nifty_form"} do |f| %>
<%= f.text_area :number, :size => "60x12" %>
<%= f.submit "Search" %>
<% end
What will be the definition of search Method in ProductController and routes i need to add in routes.rb?
Irrespective of nifty forms, this is how I would have done this:
In config/routes.rb
replace resources :products' with
resources :products do
post 'search', :on => :collection
end
This will give me a search_products_path
In your view:
<%= form_for(:search, :url => search_products_path) do |f| %>
<%= f.text_field :number, :placeholder => "Enter number to search" %>
<%= f.submit "Search" %>
<% end %>
In your products_controller.rb
def search
number = params[:search][:number]
#result = Product.find_by_number(number)
#not_found = true unless #result
end
In your views/products/search.html.erb, use #result to show the product information; take care while checking whether or not the desired product is actually found or not. I have set the boolean #not_found in case it doesn't exist.

Keep params after render Ruby on Rails

I have a Project that belongs to User. In my user view I have a link to add a new project, with the parameter for the user I want to add the project to.
<%= link_to 'Add new project', :controller => "project", :action => "new", :id => #user %>
Url: /projects/new?id=62
Adding a project to a user works. The problem is when the validation fails while adding a new project and I do a render.
def create
#project = Project.new(params[:project])
if #project.save
redirect_to :action => "show", :id => #project.id
else
render :action => "new"
end
end
view:
<%= form_for #project do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.hidden_field :user_id , :value => params[:id] %>
<%= f.submit "Create project" %>
<% end %>
routes
resources :users do
resources :projects
end
How can I keep the parameter for the user after the render? Or is there some better way to do this? Been looking at a lot of similar questions but can't get it to work.
try
render :action => "new", :id => #project.id
if its not works for you, then try alternate way to pass the parameter to your render action.
This can also help you->
Rails 3 Render => New with Parameter
You shouldn't use params[:id] to assign value to this form field. Instead, add this to your #new action in controller:
def new
#project = Project.new(user_id: params[:id])
end
and then just write this in your form:
<%= f.hidden_field :user_id %>
Because #project was defined in your #new and #create actions and because it already contains a Project instance with a user_id assigned to it, the value would automatically be added to this field.

Resources