I have a strange problem. I have 2 models Issue, Comment. Comments is nested inside Issues so for that I have the create action in comments controller as follows:
def create
#issue = Issue.find(params[:issue_id])
#comment = #issue.comments.create!(params[:comment])
respond_to do |format|
if #comment.save
format.html { redirect_to #comment, notice: 'Comment was successfully created.' }
format.json { render json: #comment, status: :created, location: #comment }
format.js #create.js.erb
else
format.html { render action: "new" }
format.json { render json: #comment.errors, status: :unprocessable_entity }
end
end
end
And my create.js.erb:
var new_comment = $("<%= escape_javascript(render(:partial => #comment))%>").hide();
$('#comments').prepend(new_comment);
$('#comment_<%= #comment.id %>').fadeIn('slow');
$('#new_comment')[0].reset();
Issue.rb
class Issue < ActiveRecord::Base
attr_accessible :category, :description, :title
has_many :comments
end
Comment.rb
class Comment < ActiveRecord::Base
attr_accessible :body, :issue_id
belongs_to :issue
end
routes.rb
resources :comments
resources :issues do
resources :comments
end
Problem: When I create a comment for which is a form partial residing on views/issues/show.html.erb. The comment gets created 4 times in the db.
I couldn't locate what the problem was and whats causing it. Please help
First, I would build the associated comment:
#comment = #issue.comments.build(params[:comment])
And then I would save the comment instance
#comment.save
And also check the Javascript, maybe you are having some problems with event bubbling and the event is being triggered twice.
I actually was working on some old Rails version where the js files were put inside the /public/assets and that was the reason for that weird behaviour. I deleted all the files inside the /public/assets folder and the app works fine now.
Related
i'm working through a tutorial to get a rails partial to display stock information using ajax. Everything is working properly and in the console I can see that the div has been updated properly, but it isn't being displayed. Here's the relevant code.
CONTROLLER
class StocksController < ApplicationController
def search
if params[:stock].present?
#stock = Stock.new_from_lookup(params[:stock])
if #stock
puts "should be working"
respond_to do |format|
format.js { render partial: 'users/result' }
end
else
puts "incorrect symbol"
flash[:danger] = "You have entered an incorrect symbol."
redirect_to my_portfolio_path
end
else
puts "nothing"
flash[:danger] = "You need to type something, what did you expect to happen?"
redirect_to my_portfolio_path
end
end
end
AJAX JS ERB
$('#results").html("<%=j (render 'users/result.html')%>")
The result of the partial is
<%if #stock%>
<div class = "well results-block">
<strong>Symbol:</strong><%= #stock.ticker%>
<strong>Name:</strong><%= #stock.name%>
<strong>Last Price:</strong><%= #stock.last_price%>
</div>
<%end%>
Let me know if there's more info you need. I'm using Rails 6.
You might want to check https://guides.rubyonrails.org/layouts_and_rendering.html#partial-layouts . You should try dropping 'partial' or add 'locals' or 'object' to render method.
all of the following render calls would all render the edit.html.erb template in the views/books directory:
render :edit
render action: :edit
render "edit"
render action: "edit"
render "books/edit"
render template: "books/edit"
You can pass an object in to this local variable via the :object option:
<%= render partial: "customer", object: #new_customer %>
In your case,
format.js { render 'users/result' }
Instead of using
$('#results").html("<%=j (render 'users/result.html')%>")
Did you try to use
document.querySelector('#results').innerHTML = '<%= j render 'users/result.html' %>'
This works fine for me.
I'm trying to implement this Angularjs upload in my rails application:
Angular File upload
This is my photos_controller:
def create
#photo = current_user.photos.new(photo_params)
respond_to do |format|
if #photo.save
format.html { redirect_to #photo, notice: 'Photo was successfully created.' }
format.json { render action: 'show', status: :created, location: #photo }
else
format.html { render action: 'new' }
format.json { render json: #photo.errors, status: :unprocessable_entity }
end
end
end
def photo_params
params.require(:photo).permit(:album_id, :user_id, :title, :description, :path)
end
I think that I'm close of the solution. When I try to upload I get this error:
param is missing or the value is empty: photo
Extracted source (around line #92):
9091929394
# Never trust parameters from the scary internet, only allow the white list through.
def photo_params
params.require(:photo).permit(:album_id, :user_id, :title, :description, :path)
end
end
I think that I need to format the data send to a format like this, isn't?
{"photo"=>{"tmpname"=>"253", "etc"=>"1"}}
The terminal log:
my html input:
<input type="file" nv-file-select="" name="photo[path]" id="photo_path" uploader="uploader" multiple /><br/>
My column with paper clip is path
I'm not getting how I do this in this angular script.
I don't have the rep to comment yet but usually this error comes from a naming issue, make sure your fields are named following the rails convention for example "photo[path]"
I have a form which allows users to post an update. Once the users post the update I would like the list of updates to refresh. To achieve this I'm using Ajax and jQuery and using Rails. I'm running into trouble while trying to get jquery to render the post feed partial though.
Here's the jquery I'm using
$(".microposts").html("<%= j render partial: 'shared/feed_item', collection: #feed_items %>")
At the moment, the feed just refreshes and displays nothing. I believe it's due to the way I'm trying to pass the #feed_items. What's the best way to pass that variable?
Someone asked for the controller;
class MicropostsController < ApplicationController
before_action :signed_in_user, only: [:create, :destroy]
before_action :correct_user, only: :destroy
def create
#micropost = current_user.microposts.build(micropost_params)
if #micropost.save
respond_to do |format|
format.html { redirect_to root_url }
format.js
end
else
#feed_items = []
flash[:error] = "Failed to create micropost!"
render 'static_pages/home'
end
end
def destroy
#micropost.destroy
flash[:success] = "Micropost deleted!"
redirect_to root_url
end
private
def micropost_params
params.require(:micropost).permit(:content)
end
def correct_user
#micropost = current_user.microposts.find_by(id: params[:id])
redirect_to root_url if #micropost.nil?
end
end
#feed_items needs to be defined somewhere in the controller. The # is a special symbol in Ruby that signifies an instance variable of the current class. If you define it somewhere else, it becomes an instance variable of that class.
Rails has some special magic that makes the instance variables of the controller available in the view. If it's not an instance variable on the controller, it won't work.
def create
#micropost = current_user.microposts.build(micropost_params)
if #micropost.save
#feed_items = #micropost.do_whatever_to_build_the_feed_items
respond_to do |format|
format.html { redirect_to root_url }
format.js
end
else
#feed_items = []
flash[:error] = "Failed to create micropost!"
render 'static_pages/home'
end
end
I'm using the jQuery plugin Raty for my ruby on rails 4.0 application and it seems to be working except the images for the stars aren't loading onto the screen.
So those images should be stars ^ When I mouseover them in the console while running web brick the following is outputted. (My scaffold is called reviews)
Started GET "/reviews/star-off.png" for 127.0.0.1 at 2014-03-28 14:15:42 -0400
Processing by ReviewsController#show as PNG
Parameters: {"id"=>"star-off"}
Review Load (1.3ms) SELECT "reviews".* FROM "reviews" WHERE "reviews"."id" = $1 LIMIT 1 [["id", "star-off"]]
Completed 404 Not Found in 2ms
ActiveRecord::RecordNotFound (Couldn't find Review with id=star-off):
app/controllers/reviews_controller.rb:67:in `set_review'
I currently have the star images in apps/assets/javascripts/images but have also tried to put them in app/assets/images and app/views/reviews but they still won't show up. Is my issue that they aren't in the correct directory (and if so, which directory should they be in) or do I need to add some code manually to my reviews controller? Thanks.
edit: So when I try to use it in my index page, I only get an error saying this, so I must have to do something to my routes.rb file?
ActionController::RoutingError (NNo route matches [GET] "/star-off.png")
edit: as requested here is routes.rb
ConcertReview::Application.routes.draw do
resources :reviews
get "review/index"
get "review/artist"
get "review/date"
get "review/venue"
get "review/genre"
get "review/comments"
root 'reviews#index'
get 'reviews/' => 'reviews#index'
end
and here's reviews_controller.rb (autogenerated from scaffold and have not modified)
class ReviewsController < ApplicationController
before_action :set_review, only: [:show, :edit, :update, :destroy]
# GET /reviews
# GET /reviews.json
def index
#reviews = Review.all
end
# GET /reviews/1
# GET /reviews/1.json
def show
end
# GET /reviews/new
def new
#review = Review.new
end
# GET /reviews/1/edit
def edit
end
# POST /reviews
# POST /reviews.json
def create
#review = Review.new(review_params)
respond_to do |format|
if #review.save
format.html { redirect_to #review, notice: 'Review was successfully created.' }
format.json { render action: 'show', status: :created, location: #review }
else
format.html { render action: 'new' }
format.json { render json: #review.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /reviews/1
# PATCH/PUT /reviews/1.json
def update
respond_to do |format|
if #review.update(review_params)
format.html { redirect_to #review, notice: 'Review was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #review.errors, status: :unprocessable_entity }
end
end
end
# DELETE /reviews/1
# DELETE /reviews/1.json
def destroy
#review.destroy
respond_to do |format|
format.html { redirect_to reviews_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_review
#review = Review.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def review_params
params.require(:review).permit(:artist, :venue, :date, :genre, :sound, :stagePresence, :songSelection, :overallRating, :comments)
end
end
I had that very same problem on my project. The star images do belong in app/assets/images like you tried. However, you need to pass raty a path option like such:
$('div').raty({
readOnly: true,
halfScore: true,
score: 3,
path: '/assets'
});
This is working for me.
Also, if you have turbolinks on, you're going to have to tweek any $(document).ready(function () {...}); you might have. That was the problem I had right after this one.
I am trying to destroy a comment through Ajax. In my app, my comment model uses a polymorphic association. The comment deletes successfully (in the database) using the code below. However, when I call the destroy.js.erb, it doesn't do anything and I think the problem is that the dom_id doesn't match the HTML id, so it is not updating. I think I am experiencing the same thing that #mu_is_too_short articulated in the answer to this question. I need help with how to solve this though. I do not know if the solution involves a) somehow passing the local variable comment to the destory.js.erb or b) another solution.
routes.rb
resources :feeds do
resources :comments
end
destroy.js.erb
$('#<%= dom_id(#comment) %>')
.fadeOut ->
$(this).remove()
_comment.html.erb
<div id=<%= dom_id(comment) %> class="comment">
<em>on <%= comment.created_at.strftime('%b %d, %Y at %I:%M %p') %></em>
<%= link_to "Remove", [#commentable, comment], :method => :delete, :remote => true %>
<%= simple_format comment.content %>
</div>
feeds/show.html.erb
<div id="comments">
<%= render #comments %>
</div>
Comments controller
class CommentsController < ApplicationController
def create
#comment = #commentable.comments.new(params[:comment])
if #comment.save
respond_to do |format|
format.html { redirect_to #commentable }
format.js
end
else
render :new
end
end
def destroy
#comment = Comment.find(params[:id])
#commentable = #comment.commentable
if #comment.destroy
respond_to do |format|
format.html { redirect_to #commentable }
format.js
end
end
end
end
Feeds controller
class FeedsController < ApplicationController
def show
#feed = Feed.find(params[:id])
#commentable = #feed
#comments = #commentable.comments
#comment = Comment.new
end
end
By the looks of it, #comment will contain a comment when you get to destroy.js.erb, as you set it in the controller immediately before that, so I do not think it has anything to do with the referenced answer. I wonder if this is being caused by the lack of quotes around your id here: <div id=<%= dom_id(comment) %> class="comment">... I suspect if you correct this, and any other relevant HTML validation errors, it will start working.