Rails 'stringify_keys' - ruby-on-rails

(sorry for my english)
I'm trying my first rails web app.
Here is my code:
Model:
class Movie < ActiveRecord::Base
attr_accessible :about, :title, :url
end
Controller:
class MoviesController < ApplicationController
def show
#movie = Movie.find(params[:id])
end
def update
#mov = Movie.find(params[:id])
if #mov.update_attributes(params[:id])
redirect_to movies_path, :notice => "Your movie has been updated."
else
render "show"
end
end
def destroy
end
end
and the View
<%= form_for #movie do |m| %>
<center>
<table>
<td valign='middle' align='right'>
Title:
</td>
<td>
<%= m.text_field :title %>
</td>
<tr>
<td valign='middle' align='right'>
Description:
</td>
<td>
<%= m.text_area :about %>
</td>
<tr>
<td valign='middle' align='right'>
URL:
</td>
<td>
<%= m.text_field :url, :id => "url" %><input type='file' onchange="document.getElementById('url').value = this.value" />
</td>
<tr>
<td>
</td>
<td>
<center>
<%= m.submit %>
</center>
</td>
</table>
</center>
<% end %>
so this is an update action and this give an error message after press the update form button
error is:
undefined method `stringify_keys' for "15":String
so I try again with Movie.find(params[:id].to_i) and the output is:
undefined method `stringify_keys' for 15:Fixnum
thanks for answers, have a good day!=)

if #mov.update_attributes(params[:id])
Its because of the above line. Here you are trying to update the #mov attribute with the params[:id] which is wrong.
the update action in the controller should be as follow.
def update
#mov = Movie.find(params[:id])
if #mov.update_attributes(params[:movie])
redirect_to movies_path, :notice => "Your movie has been updated."
else
render "show"
end
end
Basically the update_attributes will check for hash as a parameter like below.
#mov.update_attributes(:about => "Sample About", :title => "Sample Title", :url => "Sample URL")

Related

How to edit data onclick button using rails gem 'best_in_place'?

I am using rails gem 'best_in_place' and data edit one by one, as clicked perticular field.
how can i active all fields for editable onclick update/edit button?
def update
if m_user[:name].present?
MUser.where(:id => id).update(:name => m_user[:name])
elsif m_user[:gender].present?
MUser.where(:id => id).update(:gender => m_user[:gender])
else
flash[:danger] = 'not updated'
end
end
View code:
<% #user.each do |record| %>
<tr>
<td>
<%= best_in_place record, :name, :as => :input %>
</td>
<td>
<%= best_in_place record, :gender, :as => :select, collection: (MUser.pluck(:id,:gender)) %>
</td>
<%= best_in_place record, :dob, :as => :date, class: 'datepicker1 %>
</td>
</tr>
<% end %>
<%= submit_tag('update',:name => 'update_data', class: 'btn btn-primary btn-sm', :id => 'update_btn') %>
Now data edit like if i edit name it will automatically editable
,but how can I edit when i clicked update/edit button then make all fields active for edit.
As we discussed, you need to do a couple of changes
Add a _user.html.erb partial to render the records with below code.
<td>
<%= user.name %>
</td>
<td>
<%= user.gender %>
</td>
<td>
<%= user.dob %>
</td>
<td>
<%= link_to "Edit", edit_user_path(user), remote: true %>
<td>
Now change your index.html.erb code like below.
<% #users.each do |user| %>
<tr id="record-row-<%= user.id %>">
<%= render prtial: 'user', locals: { user: user } %>
</tr>
<% end %>
Now refresh your page and you will see the User records in table rows.
Add a new partial _user_form.html.erb to render the form and add below code in it.
<td colspan="4">
<%= form_for(#user, remote: true) do |f|
<table>
<tbody>
<tr>
<td><%= f.text_field :name, class: 'form-control' %></td>
<td><%= f.select :gender, MUser.pluck(:gender, :id).uniq, { selected: #user.gender }, class: 'form-control' %></td>
<td><%= f.text_field :name, class: 'form-control datepicker1' %></td>
<td><%= f.submit "Update" %></td>
</tr>
</tbody>
</table>
<% end %>
</td>
Now need to update edit and update actions.
edit action
def edit
#user = User.find(params[:id])
respond_to do |format|
format.js { }
format.html { render 'edit' }
end
end
update action
def update
#user = User.find(params[:id])
respond_to do |format|
if #user.update_attributes(user_params)
format.js { }
format.html { redirect_to #user, notice: 'User was updated successfully.' }
else
format.js { }
format.html { render 'edit' }
end
end
end
private
def user_params
params.require(:user).permit(:name, :gender, :dob)
end
Now you need to create an edit.js.erb file to render the form on selected row.
$("#record-row-<%= #user.id %>").html("<%= escape_javascript(render 'user_form') %>")
And you also need an update.js.erb file to update the table row after updating the user record.
$("#record-row-<%= #user.id %>").html("<%= escape_javascript(render partial: 'user', locals: { user: #user } ) %>")
Now all set. Refresh your page and click on Edit button of a row. A form will appear. Change the value and click on Update button. You will see the updated record.
Let me know if you have nay issues. Happy to help.

How to update multiple record in rails 6

my controller
class IndustryController < ApplicationController
def index
#industries=Industry.all
end
def new
#industry=Industry.new
end
def create
#industry = Industry.new(industry_params)
# #industry = Industry.new(params[:name_bef,:name,:status])
# #industry = Industry.new(:name_bef => (params[:name]),:name => (params[:name]), :status => (params[:status]))
if #industry.save
redirect_to industry_index_path
else
render 'new'
end
end
def update
#industry = Industry.all
#industry.each do |i|
#industry.find(i.id)
#industry.update(industry_params)
end
end
private
def industry_params
params.require(:industry).permit(:name, :status)
end
private
def industry_update
params.require(:industry).permit(:name, :status)
end
end
my html
<%= form_for #industries, as: :industry, url: industry_path(#industries), method: :patch do |f| %>
<table class="table table-bordered">
<thead class="bg-light">
<tr>
<th scope="col">業種名(変更前)</th>
<th scope="col">業種名</th>
<th scope="col">状態</th>
</tr>
</thead>
<tbody>
<% #industries.each do |industry| %>
<tr>
<td><%= industry.name %></td>
<td>
<div class="form-group">
<%= f.text_field :name, :value => industry.name, :id => industry.id, :class => "form-control" %>
</div>
</td>
<td>
</td>
</tr>
<% end %>
</tbody>
</table>
<div class="form-group text-center">
<%= f.submit"登録", :class => " btn btn-success" %>
</div>
<%end%>
My assumption is that you are talking about the update action in your controller. It looks like update_all is the method you are looking for.
def update
Industry.update_all(industry_params)
end
This can be dangerous - be aware that this will bypass active record validations and callbacks, so make sure you are certain.

Rails: Search bar isn't working

I'm trying to add a search bar for a database website I created, I found a tutorial and I "think" I did it correct.
When I do a search, such as "Judy Zhang", nothing shows up, even though it is in the database
my vendor.rb/concerns/models/app file
class Vendor < ApplicationRecord
has_many :fotos
def self.search(search)
if search
Vendor.where('lower(contact_name) LIKE ?', "'%#{search.downcase}%'")
else
Vendor.all
end
end
end
I believe I didn't do the coding right. Very new to ruby on rails. What did I do wrong here?
code for index.html.erb/vendors/views/layouts/app
<body>
<div class = "head">
<h1>Vendors </h1>
<div class = "image1" >
<img src= "http://dx.deucex.com/i/logo.png" >
</div>
</div>
</body>
<table>
<tr>
<%= button_to "New Vendor", new_vendor_path, :method => "get" %>
<%= button_to "Inventory", inventories_path, :method => "get" %>
<%= form_tag vendors_path, :method => 'get' do %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
<% end %>
</tr>
</table>
<table>
<tr>
<th>Company</th>
<th>Contact Name</th>
<th>Phone</th>
<th>Email</th>
</tr>
<% for vendor in #vendors %>
<tr>
<td><%= vendor.company %></td>
<td><%= vendor.contact_name %></td>
<td><%= vendor.phone %></td>
<td><%= vendor.email %></td>
<body>
<div class = "button1" >
<td><%= button_to "Show", vendor_path(vendor), :method => "get" %></td>
</div>
</body>
<td><%= button_to "Edit", edit_vendor_path(vendor), :method => "get" %></td>
<div class = "button3">
<td><%= button_to 'Delete',
vendor_path(vendor),
method: :delete,
data: { confirm: 'Are you sure?'} %></td>
</div>
</tr>
<% end %>
</table>
code for my VendorsController.rb/concerns/controller/app
class VendorsController < ApplicationController
def index
#vendors = Vendor.search(params[:search])
end
def show
#vendor = Vendor.find(params[:id])
end
def new
#vendor = Vendor.new
end
def create
#vendor = Vendor.new(vendor_params)
if #vendor.save
redirect_to #vendor
else
render 'new'
end
end
def edit
#vendor = Vendor.find(params[:id])
end
def update
#vendor = Vendor.find(params[:id])
if #vendor.update (vendor_params)
redirect_to #vendor
else
render 'edit'
end
end
def destroy
#vendor = Vendor.find(params[:id])
#vendor.destroy
redirect_to vendors_path
end
end
private
def vendor_params
params.require(:vendor).permit(:company, :contact_name, :phone, :email, :moq, :cost_per_item, :payment_method, :terms, :turnover, :returns, :notes)
end
Try changing the code in Vendor to
class Vendor < ApplicationRecord
has_many :fotos
def self.search(search)
if search
Vendor.where('lower(name) LIKE ?', "'%#{search.downcase}%'")
else
Vendor.all
end
end
end
My search bar isn't showing up
You should change the following
<% form_tag vendors_path, :method => 'get' do %>
to
<%= form_tag vendors_path, :method => 'get' do %>
# Notice that <%= %> evaluates and prints the output

undefined 'items' for nil class

on my e-store website when I try to checkout my cart, I'm getting
undefined method `items' for nil:NilClass.
Although on the error page
I know that my cart is there... but when I call it, it gives me nil
Cart Model
class Cart
attr_reader :items
def self.build_from_hash hash
items = if hash["cart"] then
hash["cart"]["items"].map do |item_data|
CartItem.new item_data["product_id"], item_data["quantity"]
end
else
[]
end
new items
end
def initialize items = []
#items = items
end
def add_item product_id
item = #items.find { |item| item.product_id == product_id }
if item
item.increment
else
#items << CartItem.new(product_id)
end
end
def empty?
#items.empty?
end
def count
#items.length
end
def serialize
items = #items.map do |item|
{
"product_id" => item.product_id,
"quantity" => item.quantity
}
end
{
"items" => items
}
end
def total_price
#items.inject(0) { |sum, item| sum + item.total_price }
end
end
Application Controller
def initialize_cart
#cart = Cart.build_from_hash session
end
Cart Controller
class CartsController < ApplicationController
before_filter :initialize_cart
def add
#cart.add_item params[:id]
session["cart"] = #cart.serialize
product = Product.find params[:id]
redirect_to :back, notice: "Added #{product.name} to cart."
end
def show
end
def checkout
#order_form = OrderForm.new user: User.new
end
end
Order Controller
class OrdersController
def create
#order_form = OrderForm.new(
user: User.new(order_params[:user]),
cart: #cart
)
if #order_form.save
redirect_to '/', notice: "Thank you for placing your order."
#cart.empty?
else
render 'carts/checkout'
end
end
Checkout View
<div class="container-checkout">
<p class="text-title"> You are checking out the following: </p>
<table class="table table-striped">
<thead class="name-table">
<tr>
<td> Image </td>
<td> Name </td>
<td> Category</td>
<td> Size </td>
<td> Item Price </td>
</tr>
</thead>
<tbody>
<% #cart.items.each do |item| %>
<tr>
<td><img src="<%= item.product.image %>" width="50px"></td>
<td><%= item.product.name.capitalize %></td>
<td><%= item.product.category.name %></td>
<td><%= item.product.size %></td>
<td class="price-item"><%= number_to_currency item.total_price %>
</td>
<% end %>
</tr>
<tr class="total-price total-price-checkout">
<td class="name-table">Total Price</td>
<td class="price-item"><%= number_to_currency #cart.total_price %></td>
</tr>
</tbody>
</table>
</div>
<div class="details-user-form">
<%= form_for #order_form, url: orders_path do |f|%>
<% f.fields_for :user, #order_form.user do |u| %>
<p class="text-title">Fill the form with your details</p>
<p><%= render "orders/errors" %></p>
<p><%= u.text_field :name, placeholder: "Name" %></p>
<p><%= u.text_field :email, placeholder: "Email" %></p>
<p><%= u.text_field :address, placeholder: "Address" %></p>
<p><%= u.text_field :postal_code, placeholder: "Postal code" %></p>
<p><%= u.text_field :city, placeholder: "City" %></p>
<p><%= u.text_field :country, placeholder: "Country" %></p>
<%= f.submit "Place order", class: "order-btn"%><br>
<% end %>
<% end %>
</div>
Any idea of why is it doing so? Also because, it was working before.. I don't know why it stopped.
I think the problem may be that the #cart variable isn't being set in the OrdersController. Setting the variable in CartsController doesn't make it available globally, as it would only be scoped to the controller that created it, in your case the CartsController.
Also, I see that your Cart model is more of a virtual model than an ActiveRecord model, is that the behaviour you were looking for as I believe ActiveRecord already has a lot of the methods you're recreating there.
I'm not totally sure but I think these may be the issues.
UPDATE
I think I found your error.
In your OrdersController you should have a
before_action :initialize_cart
That seems to be coming from your ApplicationController
If you check your checkout method in your CartController, you will see that you did not set #cart. So when you hit the checkout view, it comes to look for the value or #cart in this method. Setting it there, like the code below should clear your error.
def checkout
#order_form = OrderForm.new user: User.new
#cart = # cart object
end

Rails syntax error </div>

I am trying to set "edit" function for a simple CMS. I can make it to create/delete, but it just won't let me "edit".
here is the error message:
SyntaxError in SectionsController#edit
app/views/sections/edit.html.erb:42: syntax error, unexpected keyword_ensure, expecting keyword_end
Extracted source (around line #42):
40
41
when I checked my edit.html.erb. it seems fine?
'index'}, :class => 'back-link') %>
<div class="sections edit">
<h2>Update Sections</h2>
<%= form_for(:two, :url => {:action => 'update', :id => #one.id}) do |f| %>
<table summary="Section form fields">
<% #one.each do |f| %>
<tr>
<th>Name</th>
<td><%= f.text_field(:name) %></td>
</tr>
<tr>
<th>Position</th>
<td><%= f.text_field(:position) %></td>
</tr>
<tr>
<th>Visible</th>
<td><%= f.text_field(:visible) %></td>
</tr>
<tr>
<th>content_type</th>
<td><%= f.text_field(:content_type) %></td>
</tr>
<tr>
<th>content</th>
<td><%= f.text_field(:content) %></td>
</tr>
<tr>
<th>page_id</th>
<td><%= f.text_field(:page_id) %></td>
</tr>
</table>
<div class="form-buttons">
<%= submit_tag("Update Section") %>
</div>
<% end %>
</div>
Here is the controller:
class SectionsController < ApplicationController
def index
#one = Section.all
end
def show
#one = Section.find(params[:id])
end
def new
#one = Section.new
end
def create
#one = Section.new(section_params)
if #one.save
flash[:notice] = "Section created successfully!"
redirect_to(:action => 'index')
else
render('new')
end
end
def edit
#one = Section.find(params[:id])
end
def update
#one = Section.find(params[:id])
if #one.update_attributes(section_params)
flash[:notice] = "Subject updated successfully!"
redirect_to(:action => 'show', :id =>#one.id)
else
render('edit')
end
end
def delete
#one = Section.find(params[:id])
end
def destroy
subject = Section.find(params[:id]).destroy
flash[:notice] = "Subject deleted successfully!"
redirect_to(:action => 'index')
end
private
def section_params
params.require(:two).permit(:id,:name,:position,:visible,:page_id,:content,:content_type)
end
end
Thanks so much!!
Thanks #Pavan, #MarsAtomic and #Mandeep ! I found the issue: <% #one.each do |f| %>. I don't really need this line. If I need it, I need a end code for this.
In my case, I don't, so I go ahead deleted this line, and it worked now!
thanks again everyone!

Resources