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!
Related
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
This is the error I get.
This is my model code.
class Subject < ActiveRecord::Base
has_many :pages
validates :name,
:presence => true,
:length => { :maximum => 255 }
scope :visible, lambda { where(:visible => true) }
scope :invisible, lambda { where(:visible => false) }
scope :sorted, lambda { order("subjects.position ASC")}
scope :newest_first, lambda { order("subject.created_at DESC") }
scope :search, lambda { |query|
where(["name LIKE ?", "%#{query}%"])
}
end
I noticed that it's saying something about my create action. So here's that:
class SubjectsController < ApplicationController
layout "admin"
def index
#subjects = Subject.sorted
end
def show
#subject = Subject.find(params[:id])
end
def new
#subject = Subject.new({:name => 'Default'})
#subject_count = Subject.count + 1
end
def create
# Instantiate a new object using form parameters
#subject = Subject.new(subject_params)
# Save the object
if #subject.save
# If save succeeds, redirect to the index
flash[:notice] = "The subject was created successfully."
redirect_to(:action => 'index')
else
#subject_count = Subject.count + 1
render(new)
end
end
def edit
#subject = Subject.find(params[:id])
#subject_count = Subject.count
end
def update
# Find an existing object using form parameters
#subject = Subject.find(params[:id])
# Update the object
if #subject.update_attributes(subject_params)
# If save succeeds, redirect to the show
flash[:notice] = "The subject was updated successfully."
redirect_to(:action => 'show', :id => #subject.id)
else
# If update fails, redisplay the form so user can fix problem.
#subject_count = Subject.count
render('edit')
end
end
def delete
#subject = Subject.find(params[:id])
end
def destroy
subject = Subject.find(params[:id]).destroy
flash[:notice] = "The subject '#{subject.name}' was deleted successfully."
redirect_to(:action => 'index')
end
private
def subject_params
# same as using "params[:subject]", except that it:
# -raises an error if :subject is not present
# -allows listed attributes to be mass-assigned
params.require(:subject).permit(:name, :position, :visible)
end
end
If I take the validations off it works, but then I can create the subject without a name. I noticed that if I add a subject the number in the paranthesis '3' moves up. I wonder if it has something to do with the select form. Here's the form:
<%= error_messages_for(#subject) %>
<table summary="Subject form fields" class="table table-hover">
<tr>
<th><%= f.label(:name, "Name") %></th>
<td><%= f.text_field(:name) %></td>
</tr>
<tr>
<th><%= f.label(:position) %></th>
<td><%= f.select(:position, 1..#subject_count) %></td>
</tr>
<tr>
<th><%= f.label(:visible) %></th>
<td><%= f.check_box(:visible) %></td>
</tr>
</table>
Update: I'm adding the index view per request.
<% #page_title = 'Subjects' %>
<div class="subjects show">
<h2>Subjects</h2>
<%= link_to("Add New Subject", {:action => 'new'}, :class => 'action new btn btn-default') %>
<table class="listing table table-hover" summary="Subject list">
<tr class="header">
<th>Position</th>
<th>Subject</th>
<th>Visible</th>
<th>Pages</th>
<th>Actions</th>
</tr>
<% #subjects.each do |subject| %>
<tr>
<td><%= subject.position %></td>
<td><%= subject.name %></td>
<td class="center"><%= subject.visible ? 'Yes' : 'No' %></td>
<td class="center"><%= subject.pages.size %></td>
<td class="actions">
<%= link_to("Show", {:action => 'show', :id => subject.id}, :class => 'action show') %>
<%= link_to("Edit", {:action => 'edit', :id => subject.id}, :class => 'action edit') %>
<%= link_to("Delete", {:action => 'delete', :id => subject.id}, :class => 'action delete') %>
</td>
</tr>
<% end %>
</table>
</div>
due to a syntax error for the partial on the else part of create action, active model was throwing an exception(http://apidock.com/rails/v3.2.1/ActionView/PartialRenderer/partial_path)
def create
#few lines escaped....
else
#subject_count = Subject.count + 1
render(new) # <-- Error
end
It should be either render :new or render 'new' as mentioned by Nobilik. your method should look like:
def create
#few lines escaped....
else
#subject_count = Subject.count + 1
render :new # for best practice
end
I am learning to use CRUD, and setup a page to add a record, however it only generated blank record? Can you take a look my code?
thanks!
here is the Page controller:
class PagesController < ApplicationController
def index
#test = Page.all
end
def new
#test = Page.new
end
def create
#test = Page.new(params.permit(:subject_id,:name,:position,:visible,:permalink))
if #test.save
flash[:notice] = "Page created successfully!"
redirect_to(:action => 'index')
else
render('new')
end
end
end
here is the new.html.erb
<%= link_to("<< Back to List", {:action => 'index'}, :class => 'back-link') %>
<div class="pages new">
<h2>Create Subject</h2>
<%= form_for(:Page, :url => {:action => 'create'}) do |f| %>
<table summary="Page form fields">
<tr>
<th>Subject_ID</th>
<td><%= f.text_field(:subject_id) %></td>
</tr>
<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>Permalink</th>
<td><%= f.text_field(:permalink) %></td>
</tr>
</table>
<div class="form-buttons">
<%= submit_tag("Create Subject") %>
</div>
<% end %>
</div>
Here is index.html.erb
<div class="pages index">
<h2>Pages</h2>
# <%= link_to("Add New Page", {:action => 'new'}, :class => 'action new') %>
<table class="listing" summary="Page list">
<tr class="header">
<th>Position</th>
<th>Page Name</th>
<th>Visible</th>
<th>Pages</th>
<th>Actions</th>
</tr>
<% #test.each do |f| %>
<tr>
<td><%= f.position %></td>
<td><%= f.name %></td>
<td class="center"><%= f.visible %></td>
<td class="center"><%= f.permalink %></td>
<td class="actions">
<%= link_to("Show", {:action => 'show', :id => f.id}, :class => 'action show') %>
<%= link_to("Edit", {:action => 'edit', :id => f.id}, :class => 'action edit') %>
<%= link_to("Delete", {:action => 'delete', :id => f.id}, :class => 'action delete') %>
</td>
</tr>
<% end %>
</table>
</div>
Thanks so much!
Strong parameters
Rails sends form parameters in nested hashes.
{ page: { subject_id: 1, name: 'Hello World.' } }
So to whitelist the parameters you would do.
class PagesController < ApplicationController
def index
#test = Page.all
end
def new
#test = Page.new
end
def create
#test = Page.new(page_params)
if #test.save
flash[:notice] = "Page created successfully!"
redirect_to(:action => 'index')
else
render('new')
end
end
private
def page_parameters
params.require(:page)
.permit(:subject_id,:name,:position,:visible,:permalink)
end
end
which is like doing:
params[:page].slice(:subject_id,:name,:position,:visible,:permalink)
form_for and models
Also your form should read:
<%= form_for(:page, :url => {:action => 'create'}) do |f| %>
Or:
<%= form_for(#page, :url => {:action => 'create'}) do |f| %>
:Page will give you the wrong key in your parameters and prevent rails from binding the form to your #page object. (The values posted will disappear from the form when it's invalid).
I'm working through the rails intro guide but using 'stocks' instead of 'articles' and 'time_detlas' instead of 'comments' my issue is that it seems to be saving time_deltas correctly, I think I checked that correctly but the show of the stock just adds an extra blank row to the table of time_deltas no numbers show. Any suggestions why?
Stocks controller:
class StocksController < ApplicationController
def new
#stock = Stock.new
end
def index
#stocks = Stock.all
end
def create
# XXX Add columns for delta and current standing when we get there
# they can intiate to nil
#stock = Stock.new(stock_params)
if #stock.save
redirect_to #stock
else
render 'new'
end
end
def show
#stock = find_stock
#time_delta = #stock.time_deltas.build
end
def edit
#stock = find_stock
end
def update
#stock = find_stock
if #stock.update(stock_params)
redirect_to #stock
else
render 'edit'
end
end
def destroy
#stock = find_stock
#stock.destroy
redirect_to stocks_path
end
private
def stock_params
params.require(:stock).permit(:name, :hashtag)
end
def find_stock
return Stock.find(params[:id])
end
end
Time Delta Controller
class TimeDeltasController < ApplicationController
def create
#stock = Stock.find(params[:stock_id])
#time_delta = #stock.time_deltas.create(time_delta_params)
redirect_to stock_path(#stock)
end
private
def time_delta_params
params.require(:time_delta).permit(:start, :length)
end
end
Show for the stock
<h1> Stock </h1>
<table>
<tr>
<th>Stock</th>
<th>Hashtag</th>
</tr>
<tr>
<td><%= #stock.name %></td>
<td><%= #stock.hashtag %></td>
</tr>
</table>
<h3>TimeDeltas: </h2>
<table>
<tr>
<th>Start</th>
<th>Length</th>
</tr>
<% #stock.time_deltas.each do |time_delta| %>
<tr>
<td><%= #time_delta.start %></td>
<td><%= #time_delta.length %></td>
</tr>
<% end %>
</table>
<h3>Add a TimeDelta:</h2>
<%= form_for([#stock, #stock.time_deltas.build]) do |f| %>
<p>
<%= f.label :start %><br>
<%= f.text_field :start %>
</p>
<p>
<%= f.label :length %><br>
<%= f.text_field :length %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
<%= link_to 'Back', stocks_path%>
<%= link_to 'Edit', edit_stock_path(#stock)%>
Any help is appreciated, thank you!
just remove # from time_delta
<% #stock.time_deltas.each do |time_delta| %>
<tr>
<td><%= time_delta.start %></td>
<td><%= time_delta.length %></td>
</tr>
<% end %>
up
You need # only to be able to share this var with your view. Eg: If you add this to your show action: #time_deltas = TimeDelta.all
you can show time_deltas in your view.
like:
<% #time_deltas.each do |td|%>
<%= td.start%>
<% end %>
as the title says I'm trying to list all cars of one specific user, also each car has two options show and update
as you see in the picture, my problem is when I want to show or edit the selected car, it routes (look the bottom left of the image) it takes all the ids of all the cars for example users/"id"/cars/"id1"/"id2" instead to take the id of the specific car: users/"id"/cars/"id1"/
here is te index.html.erb file:
<div class="container">
<h1>Listing Cars</h1>
<table class="table table-condensed">
<tr>
<th>Brand</th>
<th>Color</th>
<th>Model</th>
<th>Year</th>
<th></th>
<th></th>
</tr>
<% #car.each do |car| %>
<tr>
<td><%= car.brand %></td>
<td><%= car.color %></td>
<td><%= car.model %></td>
<td><%= car.year %></td>
<td><%= link_to 'Show', user_car_path(#user,#car) %></td>
<td><%= link_to 'Edit', edit_user_car_path(#user, #car) %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New car', new_user_car_path, :class => "btn btn-primary" %>
</div>
and whether you need the car controller:
class CarsController < ApplicationController
def new
#user = User.find(params[:user_id])
#car = #user.cars.build
end
def create
#user = User.find(params[:user_id])
#car = #user.cars.build(params[:car])
if #car.save
redirect_to user_car_path(#user, #car), :flash => { :notice => " car created!" }
else
redirect_to new_user_car_path ,:flash => { :notice => " sorry try again :(" }
end
end
def show
#user = User.find(params[:user_id])
#car = #user.cars.find(params[:id])
#redirect_to user_car_path(#user, #car)
end
def index
#user = User.find(params[:user_id])
#car = #user.cars.all
end
def edit
#user = User.find(params[:user_id])
#car = #user.cars.find(params[:id])
#redirect_to user_car_path(#user, #car)
end
def update
#user = User.find(params[:user_id])
#car = #user.cars.find(params[:id])
if #car.update_attributes(params[:car])
redirect_to user_cars_path, :flash => { :notice => " Car Updated!" }
else
render 'edit'
end
end
end
Inside a Ruby enumerator, the block variable is each member of the enumerator, one after the other. So if, in your sample code, #cars is ["Toyota", "Mazda", "Honda"], then car will be first "Toyota", then "Mazda", then "Honda".
This is a long way of saying you're using the instance variable when you should be using the block variable. ;) Correct your code to look like this:
<% #car.each do |car| %>
<tr>
<td><%= car.brand %></td>
<td><%= car.color %></td>
<td><%= car.model %></td>
<td><%= car.year %></td>
<td><%= link_to 'Show', user_car_path(#user, car) %></td>
<td><%= link_to 'Edit', edit_user_car_path(#user, car) %></td>
</tr>
<% end %>
It should be car, not #car, in your routes.