Link to remote destroy is not updating div - ruby-on-rails

I created a view that show all my invoices products and also created a link that remove an invoice product from a div and it will be updated so everytime that I remove everything will be in the same page.
Here is the table
invoices
|id| |name|
1 ABC
2 DEF
invoice_products
|id| |invoice_id| |word|
1 1 AAAA
2 1 BBBB
3 2 CCCC
4 2 DDDD
Here is the controller:
def show
#invoice= Invoice.find(params[:id])
end
def destroy_job
#job = InvoiceProduct.find(params[:id])
#invoice = #job.invoice
#job.destroy()
render :partial=>"finance_management/invoice/partials/new_subjects" }
end
Here is the model
class Invoice < ActiveRecord::Base
has_many :invoice_products
end
class InvoiceProduct < ActiveRecord::Base
belongs_to :invoice
end
Here is the view: "show.html.erb"
<%= #invoice.id %>
<div id="table"%>
<% #invoice.invoice_products.each do |i| %>
<%= i.name %>
<%= i.word %>
<%=link_to_remote(image_tag("image.png"), :update => "table",:url => { :controller=>'finance_management/invoice_product',:action => 'destroy_job',:id=>i.id } )%>
<% end %>
</div>
The log:
ActionView::TemplateError (undefined method `invoice_products' for nil:NilClass)
I created "delete_job.js.erb":
$('table').html("<%= j(render partial: 'finance_management/invoice/partials/new_subjects') %>");
But I got this error:
NoMethodError (undefined method `invoice_products=' for nil:NilClass):
The problem is that is not updating the div seems because getting nil error
Somebody can help me please?

According to this you must do this:
The controller invoice_controller.rb:
def show
#invoice= Invoice.find(params[:id])
#products = InvoiceProduct.find(:all,:conditions=>['invoice_id = ?',params[:id] ])
end
def destroy_job
#job = InvoiceProduct.find(params[:id])
#obj_invoice = Invoice.find(#job.invoice_id)
#job.destroy
end
The view "invoice/show.html.erb"
<%= #invoice.id %>
<div id="table"%>
<%= render :partial=>"invoice/partials/products" %>
</div>
Don't forget to create the partial view "invoice/partials/_products.erb" this will replace the div
<% #products.each do |i| %>
<%= i.name %>
<%= i.word %>
<%=link_to_remote(image_tag("image.png"),:url=>{:controller=>'invoice',:action => 'destroy_job',:id=>i.id})%>
<% end %>
Finally create "invoice/destroy_job.rjs"
page.replace_html 'table', :partial=>'invoice/partials/products'

Create a file "destroy_job.js.erb" and place render method inside this file instead of calling it in controller:
$('YOUR_ID').html("<%= j(render partial: 'finance_management/invoice/partials/new_subjects') %>");

Related

Rails AJAX link_to not refreshed controller action

In my Rails 5 app, Doctor/Admin have to create a Caregiver with linked Patient (new object CaregiverPatient represents that). During this process, inside the registrants_controller#new, Doctor/Admin search for a Patient (which is done by Ransack gem) and from the result he/she push Add Patient button to add Patient to initialized CaregiverPatient object from caregiver_patient#new and display #patient.full_name inside the form.
In order not to lose already filled form fields, everything must be done asynchronously. I've tried to do so with AJAX, below my code:
registrant_controller.rb
def new
#registrant = Registrant.new
#patient = Registrant.find(session[:patient_id_to_add_caregiver]) if session[:patient_id_to_add_caregiver]
end
registrants/_new_form.html.erb
<%= form_for #registrant do |f| %>
<%= f.fields_for :registration do |registration| %>
<% if #patient %>
<div id="add-patient"></div>
<% else %>
<%= required_text_field_group registration, #registrant, :registrant_id, "Patient Added", {}, { disabled: true } %>
<% end %>
<% end %>
# some other logic (...)
# patient search result
<% #registrants do |registrant| %>
<%= link_to 'Add Patient', new_registrant_link_path(registrant), remote: true %>
<% end %>
Add Patient button triggers caregiver_patients#new action:
#caregiver_patient_controller.rb
class CaregiverPatientsController < ApplicationController
# new_registrant_link_path
def new
session[:patient_id_to_add_caregiver] = params[:registrant_id].to_i
respond_to do |format|
format.html { redirect_to request.referer }
format.js { render action: 'patient_to_caregiver', notice: 'Patient Added' }
end
end
end
AJAX request is made:
#views/caregiver_patients/patient_to_caregiver.js.erb
$("#add-patient").html("<%= escape_javascript(render :partial => 'registrants/add_patient') %>");
views/registrants/_add_patient.html.erb
Patient Added: <%= #patient.full_name %>
But surprisingly gets an error:
ActionView::Template::Error (undefined method `full_name' for nil:NilClass):
1: Patient Added: <%= #patient.full_name %>
Which probably means that registrants_controller#new was not refreshed under the hood somehow. What have I missed?

uninitialized constant ActionView::CompiledTemplates::BlogPost

So I have the following in my blog_posts.rb model:
class BlogPost::Fetch < ActiveRecord::Base
API_URI = "http://blog.url.com/rss.xml".freeze
def class
posts = Rails.cache.fetch(API_URI, expires_in: 10.minutes) do
begin
feed = Feedjira::Feed.fetch_and_parse API_URI
feed.entries.take(2)
rescue
[]
end
end
posts
end
end
The following in my view helper:
module BlogHelper
def fetch_blog_posts(entries)
posts.each do |post|
unless exists? :guid => post.id
create!(
:title => post.title,
:pubDate => post.date
)
end
end
end
end
Then in my view:
<% BlogPost.fetch_blog_posts(2).each do |post| %>
<div class="home-blog-post">
<div class="news-date">
<%= post.display_date %>
With this present I end up with uninitialized constant ActionView::CompiledTemplates::BlogPost.
What am I missing? I feel like it's something simple that I'm just not seeing.
EDIT:
I have tried the following as well:
Added include ActiveRecord::Helpers in my model and changed the view to be BlogPost::Fetch. Same error
Put my helper method into the model and used both BlogPost::Fetch and BlogPost in the view. Same error for both.
Changed my model from inheriting from ActiveRecord::Base to Operator. Same error.
The only time I've gotten a different error is when I changed the model name to blog_post.rb and I get a circular error.
Another Edit:
I've pulled everything from the view helper as it's pointless. I'm not using a controller as it's in the CMS. So my model named fetch.rb now has the following:
class BlogPost::Fetch < ActiveRecord::Base
API_URI = 'http://blog.url.com/rss.xml'.freeze
def call
posts = Rails.cache.fetch(API_URI, expires_in: 10.minutes) do
begin
feed = Feedjira::Feed.fetch_and_parse API_URI
feed.entries.take(2)
rescue
[]
end
end
posts
end
def fetch_blog_posts
#posts = BlogPost::Fetch.run.result
end
end
Then in the view:
<% BlogPost.fetch_blog_posts(2).each do |post| %>
<div class="home-blog-post">
<div class="news-date">
<%= post.display_date %>
</div>
<%= link_to post.title, blog_post_path(post.url_name), class: 'news-title' %>
</div>
Still getting the same error.
So I tried changing my view to be:
<% #posts(2).each do |post| %>
<div class="home-blog-post">
<div class="news-date">
<%= post.display_date %>
</div>
<%= link_to post.title, blog_post_path(post.url_name), class: 'news-title' %>
</div>
In this case I end up with the error of: syntax error, unexpected '(', expecting keyword_end '.freeze; #posts(2).each do |post| ^
Took awhile but this worked. I changed the model to be:
class Fetch < ActiveRecord::Base
API_URI = 'http://blog.url.com/rss.xml'.freeze
def self.fetch_blog_posts(posts)
posts = Rails.cache.fetch(API_URI, expires_in: 10.minutes) do
begin
feed = Feedjira::Feed.fetch_and_parse API_URI
feed.entries.take(2)
rescue
[]
end
end
posts
end
end
Then updated the view to:
<% Fetch.fetch_blog_posts(2).each do |post| %>
<div class="home-blog-post">
<div class="news-date">
<%= post.published.strftime("%b %d, %Y") %>
</div>
<%= link_to post.title, post.url, class: 'news-title' %>

delayed_job_active_record - Undefined method `any?'

Attempting to send some stuff to the background with delayed_job_active_record, but how come I can't use any?? Works fine when things are not sent into the background.
undefined method `any?' for #<Delayed::Backend::ActiveRecord::Job:0x000000044b1348>
index.html.erb
<% if #products.any? %>
<div class="products">
<% #products.each do |product| %>
<%= product.name %>
<% end %>
</div>
<% else %>
<div class="products processing">
<!-- Try again later -->
</div>
<% end %>
main_controller.rb
class MainController < ApplicationController
def index
# Delay fetching
#products = Affiliate.delay.fetch
end
end
affiliate.rb
require "rest_client"
class Affiliate < ActiveRecord::Base
def self.fetch
response = RestClient::Request.execute(
:method => :get,
:url => "http://api.shopstyle.com/api/v2/products?pid=uid7849-6112293-28&fts=women&offset=0&limit=10"
)
#products = JSON.parse(response)["products"].map do |product|
product = OpenStruct.new(product)
affiliate = Affiliate.find_or_create_by(:name => product.name, :url => product.url)
affiliate.save
end
end
end
This doesn't work because #products isn't an array any more - it's a reference to a job that will get executed at some time in the future
You need a rethink of how your setup works. For example your view could poll via Ajax to see if the job has been completed. If it has then fetch the results from the DB, since you seem to be saving the API results there.

Pulling records from one table (products) depending on a value in another (department)

I have a Products table and a Departments table.
In products model:
has_one :department
In departments model:
belongs_to :products
I also have a view in my products controller that lists all departments as so:
<% #departments.each do |department| %>
<div class="column_entry">
<%= link_to image_tag(department.image_attachment), products_of_a_given_main_cat_url %>
</div>
<% end %>
Those load up fine. When I click on one of the images I want products_of_a_given_main_category view to dynamically populate with products from the department whose image I clicked.
In my products controller:
def products_of_a_given_main_cat
#products = Product.all
#department = Department.where(:name == :department)
respond_to do |format|
format.html # index.html.erb
format.json { render json: #products }
end
end
and in the view:
<div class="the_grid_prod">
<% #products.each do |product| %>
<% if product.department == #department.name %>
<div class="column_entry">
<%= link_to image_tag(product.product_image.url(:normal_page_size)), products_content_url(product.id) %>
</div>
<% end %>
<% end %>
</div>
When I click on the image for a department that I'm certain has products the page loads but there are no products. I'm certain I'm doing something very wrong but I'm not really sure what it is.
in routes file:
get 'products/products_of_a_given_main_cat' => :products_of_a_given_main_cat, :as => :products_of_a_given_main_cat
The problem is this:
#department = Department.where(:name == :department)
The :department is a symbol, not a string, and not a variable. Basically it is a number deep down, definietly not a name. Also, this will evaluate to Departments which have a name false. Don't do evaluation in the where part, only a hash.
You need the params[:department] if you get it from the request.
#department = Department.where(:name => params[:department])
Update:
Please modify your request link:
<%= link_to image_tag(department.image_attachment), products_of_a_given_main_cat_url(:department => department.name) %>
This will introduce a new parameter to the request, and it will work for you with the condition written above.
So to solve this problem I changed my associations as #TomL suggested in his comment. I also changed the following:
In products controller I deleted
#department = Department.where(:name => params[:department])
and changed
#products = Product.all
to
#products = Product.where(:department => params[:department])
The products_of_a_give_main_category_view now looks like this:
<div class="the_grid_prod">
<% #products.each do |product| %>
<div class="column_entry">
<%= link_to image_tag(product.product_image.url(:normal_page_size)), products_content_url(product.id) %>
</div>
<% end %>
</div>
Thanks to both #Matzi and #TomL for their help. It's greatly appreciated.

Passing local variable to partial inside for each loop rails 3

This is my code for rendering the partial (the #parties collection is being generated correctly, I have tested that):
<% #parties.each do |party| %>
<div class="item">
<%= render 'parties/party', :object => party %>
</div>
<% end %>
And this is the code in the partial:
<%= party.name %>
However, I get the following error:
undefined method `name' for nil:NilClass
I'm at my wits end, someone please help :-|
Also, this is the code for the controller to render the view containing the partial (The controller's called default_controller):
def index
#parties = Party.all
end
Is it of any consequence that this isn't the parties_controller?
I've tried something like below and it worked
<%= render :partial => 'party', :object => party %>
and I can access like party.name. the local variable is named after the partial name which is party here.
Note: Im assuming that your both partials are of parties_controller. So this should work.
Update:
Here is what ive tried with again
class PostsController < ApplicationController
#... ...
def index
#posts = Post.all
#comments = Comment.all #<---- Loading comments from PostsController
#... ...
end
end
#views/posts/index.html.erb
<% #comments.each do |comment| %>
<%= render :partial=>"comments/comment", :object=>comment %>
<% end %>
#views/comments/_comment.html.erb
<%= comment.body %>
And its working :)

Resources