I'm having trouble getting the current page to reload, after posting a remote form in Rails 4, to create join object in my db. It works fine for another model association in my app, but not here....
View Form:
select from dropdown which collection to assign to:
<% unless current_user == nil %>
<div class="btn-group pull-right">
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
Collect
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
<% current_user.collections.each do |collection| %>
<% unless CollectionPiece.where(:collection_id => collection.id, :piece_id => #piece.id).exists? %>
<li><%= link_to raw("<i class='glyphicon glyphicon-plus'></i> #{collection.title}"), collection_pieces_path(:collection_piece => {:piece_id => #piece.id, :collection_id => collection.id}), :remote => true, class: "", :method => :post %></li>
<% end %>
<% end %>
<li><%= link_to raw("<i class='glyphicon glyphicon-th-large'></i> New Collection"), new_collection_path, :class => "" %></li>
</ul>
</div>
<% end %>
Collection Piece controller:
class CollectionPiecesController < ApplicationController
after_action :collection_email, only: :create
def create
#collection_piece = CollectionPiece.create(collection_piece_params)
respond_to do |format|
if #collection_piece.save
format.html { redirect_to :back, notice: 'Collection was successfully created.' }
else
format.html { redirect_to :back, notice: 'Collection was not successfully created.' }
end
end
end
def destroy
#collection_piece = CollectionPiece.where(collection_piece_params)
respond_to do |format|
if #collection_piece.first.destroy
format.js { redirect_to :back, notice: 'Collection was successfully destroyed.' }
else
format.js { redirect_to :back, notice: 'Collection was not successfully destroyed.' }
end
end
end
def collection_email
#profile = current_user.profile
#piece = Piece.find(params[:collection_piece][:piece_id])
#collection = Collection.find(collection_piece_params[:collection_id])
UserMailer.collection_email(#profile.user, #piece, #collection).deliver
end
private
# Never trust parameters from the scary internet, only allow the white list through.
def collection_piece_params
params.require(:collection_piece).permit(:piece_id, :collection_id)
end
end
create.js.erb:
console.log("why you no work?");
location.reload();
Hope you can help, let me know if you need more info?
Related
Hello can you pls explain me how should I delete my task from a todo app?
My show_html_erb form looks like this:
this is my third day learning ruby i am quite confused i saw the documentation did the same but it just not listening to my commands:(
<%= form_for([#todo_list, #todo_item]) do |f| %>
<div class="input-group mb-4">
<%= f.text_field :description , class:"form-control", placeholder:'Add todo items'%>
<div class="input-group-append">
<%= f.submit 'Add', class:"btn btn-primary input-group-btn"%>
</div>
</div>
<%end%>
<ul class='list-group'>
<% #todo_list.todo_items.each do |todo_item| %>
<% if todo_item.completed?%>
<li class='list-group-item bg-light'>
<div class="d-flex justify-content-between">
<span class="text-muted">
<em> <%= todo_item.description%></em>
</span>
**<%= link_to 'DELETE',todo_list_path(todo_item),method: :delete, class:'btn btn-dark'%>** ------>> **THISSSS**
<%= link_to '#', class:'btn btn-dark' ,data:{reflex: 'click->TodoItem#mark_incomplete',id:todo_item.id} do%>
<i class='fas fa-undo-alt'></i>
<%end%>
</div>
</li>
<%else%>
<li class='list-group-item'>
<div class="d-flex justify-content-between">
<span>
<%= todo_item.description%>
</span>
<%= link_to 'Destroy', todo_list_path(todo_item),
method: :delete,
data: { confirm: 'Are you sure?' } ,class:'btn btn-dark'%> ------>> THIIIISSSSS
<%= link_to '#', class:'btn btn-info',data:{reflex: 'click->TodoItem#mark_complete',id:todo_item.id} do %>
<i class='fas fa-check'></i>
<%end%>
</div>
</li>
<%end%>
<%end%>
</ul>
</div>
what do i give wrong ,( i suppose the path , when i delete )
My todolist controller looks like this:
class TodoListsController < ApplicationController
before_action :set_todo_list, only: [:show, :edit, :update, :destroy]
# GET /todo_lists
# GET /todo_lists.json
def index
#todo_lists = TodoList.all
end
# GET /todo_lists/1
# GET /todo_lists/1.json
def show
#todo_item = TodoItem.new
end
# GET /todo_lists/new
def new
#todo_list = TodoList.new
end
# GET /todo_lists/1/edit
def edit
end
# POST /todo_lists
# POST /todo_lists.json
def create
#todo_list = TodoList.new(todo_list_params)
respond_to do |format|
if #todo_list.save
format.html { redirect_to #todo_list, notice: 'Todo list was successfully created.' }
format.json { render :show, status: :created, location: #todo_list }
else
format.html { render :new }
format.json { render json: #todo_list.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /todo_lists/1
# PATCH/PUT /todo_lists/1.json
def update
respond_to do |format|
if #todo_list.update(todo_list_params)
format.html { redirect_to #todo_list, notice: 'Todo list was successfully updated.' }
format.json { render :show, status: :ok, location: #todo_list }
else
format.html { render :edit }
format.json { render json: #todo_list.errors, status: :unprocessable_entity }
end
end
end
# DELETE /todo_lists/1
# DELETE /todo_lists/1.json
def destroy
#todo_list = TodoList.find(params[:id])
#todo_list.destroy
respond_to do |format|
format.html { redirect_to todo_lists_url, notice: 'Todo list was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_todo_list
#todo_list = TodoList.find(params[:id])
end
# Only allow a list of trusted parameters through.
def todo_list_params
params.require(:todo_list).permit(:title)
end
end
The issue is that you are not passing the correct object/path to delete. Try the below code.
<%= link_to 'Destroy', todo_item,
method: :delete,
data: { confirm: 'Are you sure?' } ,class:'btn btn-dark'%>
And I believe the html which you shared above is index.html.erb not show.html.erb
So i found the answer , what i had to do is linking the delete method like that:
<%= link_to 'Destroy', todo_list_todo_item_path(#todo_list,todo_item),
method: :delete,
data: { confirm: 'Are you sure?' } ,class:'btn btn-dark'%>
that fixed my problem ( the reason why is because as you could see in my show.html.erb file that ive used a nested scaffold )
I need to show current category name on posts index.
Insted of "Jubotron" it should shows test (when test category is chosen)
My code
Controllers
def index
#categories = Category.all
cate = params[:cate]
if !cate.nil?
#blogs = Category.find(params[:cate]).blogs
else
#blogs = Blog.all
end
end
def show
#blog = Blog.find(params[:id])
end
def new
#blog = Blog.new
end
def create
#blog = Blog.create(blog_params)
if #blog.save
redirect_to #blog
else
render :new
end
end
def edit
#finds the blog id
#blog = Blog.find(params[:id])
end
def update
#blog = Blog.find(params[:id])
if #blog.update(blog_params)
redirect_to #blog
else
render :edit
end
end
def destroy
#blog = Blog.find(params[:id])
#blog.destroy
redirect_to :action => :index
end
private
def blog_params
params.require(:blog).permit(:title, :content, category_ids: [])
end
end
before_action :set_category, only: [:show, :edit, :update, :destroy]
# GET /categories
# GET /categories.json
def index
#categories = Category.all
end
# GET /categories/1
# GET /categories/1.json
def show
end
# GET /categories/new
def new
#category = Category.new
end
# GET /categories/1/edit
def edit
end
# POST /categories
# POST /categories.json
def create
#category = Category.new(category_params)
respond_to do |format|
if #category.save
format.html { redirect_to #category, notice: 'Category was successfully created.' }
format.json { render :show, status: :created, location: #category }
else
format.html { render :new }
format.json { render json: #category.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /categories/1
# PATCH/PUT /categories/1.json
def update
respond_to do |format|
if #category.update(category_params)
format.html { redirect_to #category, notice: 'Category was successfully updated.' }
format.json { render :show, status: :ok, location: #category }
else
format.html { render :edit }
format.json { render json: #category.errors, status: :unprocessable_entity }
end
end
end
# DELETE /categories/1
# DELETE /categories/1.json
def destroy
#category.destroy
respond_to do |format|
format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_category
#category = Category.find(params[:id])
end
# Only allow a list of trusted parameters through.
def category_params
params.require(:category).permit(:category)
end
end
blogs/index.html.erb
<div class="row">
<div class="col-md-8">
<h1 style="text-align:center">Jumbotron</h1>
<%= #categories.each do |category| %>
<%= category.category %>
<% end %>
<div class="row">
<% #blogs.each do |blog| %>
<div class="col-md-6">
<div class="card mt-3">
<div class="card-body">
<h3><%= link_to blog.title, blog_path(blog.id) %></h3>
<p><%= blog.content %></p>
<%= link_to "Pokaż", blog_path(blog.id), class: 'btn btn-primary' %>
<br></br>
<div class="">
Kategoria:
<% blog.categories.each do |category| %>
<a><%= link_to category.category,blogs_path(:cate => category.id) %></a>
<% end %>
</div>
</div>
</div>
</div>
<% end %>
</div>
</div>
<div class="col-md-4">
<div class="card mt-3">
<div class="card-header">
Kategorie:
</div>
<div class="card-body">
<ul class="list-group">
<% #categories.each do |category| %>
<li class="list-group-item d-flex justify-content-between align-items-center">
<%= link_to category.category, blogs_path(:cate => category.id) %>
<span class="badge badge-primary badge-pill"><%= category.blogs.count %></span>
</li>
<% end %>
</ul>
</div>
</div>
</div>
</div>
</div>
and for example I can show category name in categories/show.htm.erb
but when I past it into Blogs index it gives me an error that category method is undefined.
<strong>Category:</strong>
<%= #category.category %>
</p> ```
Any ideas?
Your issue is where you are placing your 'Jumbotron' code. Currently, you're hardcoding the word 'Jumbotron' like this:
<h1 style="text-align:center">Jumbotron</h1>
You should move this inside the code where you are iterating over the categories:
<% #categories.each do |category| %>
<h1 style="text-align:center"><%= category.category %></h1>
<% end %>
Keep in mind, if you have more than one category, this is going to give you multiple <h1> tags; one for each category.
On the index page you are looping through the categories <% #categories.each do |category| %> thus you should use category.category and not #category.category inside the block
I have an app that allows users to add albums they like to a database. Anyone can then come along and write a review for that album. Pretty simple.
I am running into a problem where an extra record appears to be created for the reviews on each album's show page. Every album, even if it has not ever been reviewed, has an additional, seemingly empty review being displayed when I use .each to display each review in the album show page. I want to get rid of that.
Here is an image of the problem. I have used CSS to highlight reviews in red. As you can see, there is an empty review at the bottom. When I inspect the review in question, it's raty title is "Not reviewed yet!"
Here is my albums_controller:
class AlbumsController < ApplicationController
before_action :set_album, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, only: [:edit, :new, :update, :destroy]
def index
#albums = Album.all
if params[:search].nil?
#albums = Album.all.order(year: :desc).order(title: :asc).paginate(:page => params[:page], :per_page => 24)
else
#albums = #albums.where("albums.title || albums.year || albums.artist LIKE ?", "%#{params[:search]}%").order(year: :desc).order(title: :asc).paginate(:page => params[:page], :per_page => 24)
end
end
def show
if #album.reviews.blank?
#average_review = 0
else
#average_review = #album.reviews.average(:rating).round(2)
end
#review = #album.reviews.build
end
def new
#album = Album.new
end
def edit
end
def create
#album = current_user.albums.build(album_params)
respond_to do |format|
if #album.save
format.html { redirect_to #album, notice: 'Album was successfully created.' }
format.json { render :show, status: :created, location: #album }
else
format.html { render :new }
format.json { render json: #album.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #album.update(album_params)
format.html { redirect_to #album, notice: 'Album was successfully updated.' }
format.json { render :show, status: :ok, location: #album }
else
format.html { render :edit }
format.json { render json: #album.errors, status: :unprocessable_entity }
end
end
end
def destroy
#album.destroy
respond_to do |format|
format.html { redirect_to albums_url, notice: 'Album was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_album
#album = Album.find(params[:id])
end
def album_params
params.require(:album).permit(:title, :artist, :year, :cover)
end
end
Here is the album show page, which is where the extra review is being displayed:
<div class="row">
<div class="col-xs-10 col-md-6 col-md-push-3 col-xs-push-1 top bottom">
<%= image_tag #album.cover, class: 'show_image' %>
<h2><%= #album.title %></h2>
<h4><%= #album.artist %></h4>
<h5><%= #album.year %></h5>
<p class="white">Average Review<div class="average-review-rating" data-score=<%= #average_review %>></div></p>
<% if user_signed_in? %>
<% if #album.user_id == current_user.id %>
<%= link_to 'Edit', edit_album_path(#album), class: 'grey' %>
| <%= link_to 'Delete', album_path, method: :delete, data: {confirm: "Are you sure?"}, class: 'grey' %>
<% end %>
<% end %>
<br /><br />
<h4>Reviews</h4>
<% if user_signed_in? %>
<p class="grey">Write a review</p>
<%= form_for [#album, #review] do |r| %>
<div class="form-group">
<div id="rating-form">
<label>Rating</label>
</div>
</div>
<div class="form-group">
<%= r.text_area :comment, class: 'form-control', placeholder: "Write a comment" %>
</div>
<div class="form-group">
<%= r.submit "Create", class: 'btn btn-success' %>
</div>
<% end %>
<% end %>
<br />
<% #album.reviews.each do |r| %>
<div class="red">
<div class="review-rating" data-number="<%= r.rating %>">
</div>
<p class="white"><%= r.comment %></p>
<% if user_signed_in? %>
<% if current_user.id == r.user_id %>
<%= link_to 'Edit', edit_album_review_path(#album, r.id), class: 'grey' %> |
<%= link_to 'Delete', album_review_path(#album, r.id), method: :delete, data: {confirm: "Are you sure?"}, class: 'grey' %>
<% end %>
<% end %>
<br /><br />
</div>
<% end %>
</div>
</div>
<script>
$('.review-rating').raty({
readOnly: true,
score: function() {
return $(this).attr('data-number');
},
path: '/assets/'
});
$('#rating-form').raty({
path: '/assets/',
scoreName: 'review[rating]'
});
$('.average-review-rating').raty({
readOnly: true,
path: '/assets/',
score: function() {
return $(this).attr('data-score')
}
});
</script>
Any help would be very appreciated!
The problem here is on the last line of your show method: #review = #album.reviews.build. This line not only creates a new Review instance and assigns it to #review, but it also adds that instance to the array in #album.reviews. So, in your view, when you iterate over #album.reviews, you will see all of the persisted reviews as well as the one new, not persisted review that was built with build.
The easiest way to fix this would be to add this line in your view:
<% #album.reviews.each do |r| %>
<% next unless r.persisted? %>
Another solution would be to associate the new review with the album, but not on the #album instance. In the controller:
#review = Review.new(album: #album)
I think it could be because of last line in show.
#review = #album.reviews.build
It builds an empty review.
I tried to use Ajax request for creating a new object and this had been working very well. In my view file I used to set remote: true option for link_to and everything was fine.
Now I want to render my _form partial once the view file is loaded without a link, but just using a <%= render 'form' %>.
I don't understand why I am getting this error. Who can enlighten me what am I doing wrong?
views/tasks/index.html
<h3>Tasks database</h3>
<table>
<% #tasks.each do |task| %>
<tr class='tasks' id="task_<%= task.id %>">
<td>
<%= link_to user_task_path(current_user, task.id), method: :delete,
data: { confirm: 'Are you sure?' }, remote: true do %>
<i class="glyphicon glyphicon-trash"></i>
<% end %>
<a href="#" data-xeditable="true" data-pk="task" data-model='task' data-name='title'
data-url="/users/<%= current_user.id %>/tasks/<%= task.id %>" data-title="Enter title">
<i><%= task.title %></i>
</a>
</td>
</tr>
<% end %>
<tr>
<td><%= render 'form' %></td>
</tr>
</table>
controllers/tasks_controller.rb
class TasksController < ApplicationController
before_filter :authorize, only: [:edit, :new, :destroy]
def index
#tasks = current_user.tasks
end
def show
#task = Task.find(params[:id])
redirect_to users_path
end
def edit
#task = Task.find(params[:id])
end
def new
#task = Task.new
end
def create
#task = current_user.tasks.new(task_params)
respond_to do |format|
if #task.save
format.html { redirect_to user_tasks_path(current_user) }
format.js
else
format.html { render action: 'new' }
format.js
end
end
end
def update
#task = Task.find(params[:id])
respond_to do |format|
if #task.update(task_params)
format.html { redirect_to user_tasks_path(current_user), notice: 'Post successfully was updated.'}
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { head :no_content }
end
end
end
def destroy
#task = Task.find(params[:id])
#task.destroy
respond_to {|format| format.js }
end
private
def task_params
params.require(:task).permit(:title)
end
end
views/tasks/_form.html
<%= form_for [current_user, #task], remote: true do |f| %>
<%= f.text_field :title %>
<%= f.hidden_field :user_id, value: params[:user_id] %>
<%= f.submit %>
<% end %>
views/tasks/create.js
$('#new_task').remove();
$('#new_link').show();
$('.tasks').last().after("<%=j render partial: 'task', :locals => { :task => #task } %>");
setXeditable();
Here is my rake routes
Any help?
First argument in form cannot contain nil or be empty
You are rendering form in index page and you didn't set #task in index method.
You should set #task in index method
def index
#tasks = current_user.tasks
#task = Task.new
end
I have a model called Images with an uploader attached to it (Carrierwave). Images belongs to a model called Listing. After creating a listings I'm redirected to the Images index page to upload files (localhost:3000/listings/1/images)
But for some reason every time I create a listing an image it's created at the same time. There's actually no image present but it displays the "delete" link I have for each image.
<span><%= link_to 'DELETE', listing_image_path(#listing, image.id), data: { confirm: 'Are you sure?' }, :method => :delete, :class => 'delete' %></span>
Any help? Thanks.
Listings Controller
class ListingsController < ApplicationController
before_action :set_listing, only: [:show, :edit, :update, :destroy]
before_filter :authenticate_user!, :except => [:show, :index]
def index
#listings = Listing.order('created_at DESC')
respond_to do |format|
format.html
format.json { render json: #listings }
end
end
def show
end
def new
#listing = Listing.new
#listing.user = current_user
end
def edit
end
def create
#listing = Listing.new(listing_params)
#listing.user = current_user
respond_to do |format|
if #listing.save
format.html { redirect_to listing_images_path(#listing), notice: 'Post was successfully created.' }
else
format.html { render action: 'new' }
format.json { render json: #listing.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #listing.update(listing_params)
flash[:notice] = 'Deal was successfully updated.'
format.html { redirect_to #listing }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #listing.errors, status: :unprocessable_entity }
end
end
end
def destroy
#listing.destroy
respond_to do |format|
format.html { redirect_to listings_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_listing
#listing = Listing.friendly.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def listing_params
params.require(:listing).permit(:id, :condition, :description, :nickname, :price, :size, :title, :user_id)
end
end
Listings Form
<%= form_for(#listing, :html => { :class => 'form', :multipart => true }) do |f| %>
<% if #listing.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#listing.errors.count, "error") %> prohibited this listing from being saved:</h2>
<ul>
<% #listing.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div>
<%= f.label :title %>
<%= f.text_field :title, :required => true %>
</div>
<div>
<%= f.label :price %>
<%= f.text_field :price %>
</div>
<div class="actions">
<%= f.submit 'Submit', :class => 'buyNow' %>
</div>
<% end %>
Images Controller
class ImagesController < ApplicationController
before_action :set_image, only: [:show, :edit, :update, :destroy]
before_filter :load_listing
def index
#images = #listing.images.load
#image = #listing.images.new
end
def new
end
def edit
end
def create
#image = #listing.images.new(image_params)
respond_to do |format|
if #image.save
format.html { redirect_to :back, notice: 'Image was successfully created.' }
format.json { head :no_content }
else
format.html { render action: 'new' }
format.json { render json: #image.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #image.update(image_params)
format.html { redirect_to (#image.listing), notice: 'Image was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #image.errors, status: :unprocessable_entity }
end
end
end
def destroy
#image = #listing.images.find(params[:id])
#image.destroy
respond_to do |format|
format.html { redirect_to :back }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_image
#image = Image.find(params[:id])
end
def load_listing
#listing = Listing.find(params[:listing_id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def image_params
params.require(:image).permit(:file, :listing_id)
end
end
Images Index
<div>
<%= form_for [#listing, #image], :html => { :class => 'uploadImages', :multipart => true } do |f| %>
<%= f.hidden_field :listing_id %>
<div>
<%= f.label :file, 'Upload Images' %>
<%= f.file_field :file, multiple: true, name: 'image[file]' %>
</div>
<% end %>
</div>
<div id="progress"></div>
<% if #images.present? %>
<ul class="editGallery">
<% #listing.images.each do |image| %>
<li>
<%= image_tag image.file_url(:list) if image.file? %>
<span><%= link_to 'DELETE', listing_image_path(#listing, image.id), data: { confirm: 'Are you sure?' }, :method => :delete, :class => 'delete' %></span>
</li>
<% end %>
</ul>
<% end %>
The problem is this line:
#image = #listing.images.new
That's building a new image for #listing, so when you call #listing.images.each that new image is included in the images array. Check that the image has actually been saved to the database before constructing a delete link for it.
<% #listing.images.each do |image| %>
<% unless image.new_record? %>
<li>
<%= image_tag image.file_url(:list) if image.file? %>
<span><%= link_to 'DELETE', listing_image_path(#listing, image.id), data: { confirm: 'Are you sure?' }, :method => :delete, :class => 'delete' %></span>
</li>
<% end %>
<% end %>
Take a look at this part of your code:
<% if #images.present? %>
<ul class="editGallery">
<% #listing.images.each do |image| %>
<li>
<%= image_tag image.file_url(:list) if image.file? %>
<span><%= link_to 'DELETE', listing_image_path(#listing, image.id), data: { confirm: 'Are you sure?' }, :method => :delete, :class => 'delete' %></span>
</li>
<% end %>
</ul>
I believe your problem is a combination of this and your images controller index action.
When you hit the index action you create a new record #image = #listing.images.new
Now your #listing.images.each call registers on the object that hasn't been saved.