update partial with object content in rails 4 - ruby-on-rails

Well, i have a problem, and i was wondering if it could be solved with rails only.
I have setup a view (home.html.erb) vith 3 partials, like this:
<%provide :title, 'Reader'%>
<div class = "row">
<div class = "span4">
<div class = "row">
<%= render 'layouts/add_subscription'%>
</div>
<div class = "row">
<%= render 'layouts/subscription_list'%>
</div>
</div>
<div class = "span8">
<div class = "row">
<%= render 'layouts/view' %>
</div>
</div>
</div>
where subscription_list shows up a list of links pointing to the list action after a redirection, each of them with the id of the subscription:
<ul>
<% current_user.subscriptions.each do |s| %>
<li><%= link_to s.url, "/list?s_id=#{s.id}" %></li>
<% end %>
</ul>
So, each of these links points to the list action in the controller, which tries to fetch the feed list of the subscription just clicked, and update the home view with the list of titles for the selected subscription:
def list
s_id = params[:s_id]
feed = ""
if !s_id.blank?
s = Subscription.find_by(id: s_id)
feed = Feedzirra::Feed.fetch_and_parse(s.url)
#render partial: "layouts/view", :locals => {:f => feed}
end
The problem is that I'm stuck at this point. I've tried to do a redirect_to home_path with feed as a parameter, and even a render (the line before the end of the list method) to see what happened, but nothing updates 'just' the layouts/view partial:
<ul>
<% if defined? feed and !feed.blank? %>
<% f.entries.each do |entry|%>
<li><%= entry.title %></li>
<% end %>
<% end %>
</ul>
So, I was wondering if it's possible to update the partial and see the result after a page reload using only rails methods, or if it can/must be done using javascript, and a clue to how to do this. Thanks in advance.

The goal you want to achieve is to show feed entries in the home.html.erb after clicking a link.
You can do it by pointing your links to the home action instead of list so that rails will automatically render your home.html.erb view and
you have to assign the instance variable #feed so it will be visible in your view.
You can do it like this (refactored a bit):
controller
def home
s_id = params[:s_id]
if s_id.present?
s = Subscription.find_by(id: s_id)
#feed = Feedzirra::Feed.fetch_and_parse(s.url)
end
end
layout/view
<ul>
<% if #feed.present? %>
<% #feed.entries.each do |entry|%>
<li><%= entry.title %></li>
<% end %>
<% end %>
</ul>
I'm not sure what is the path to your action, I assume here that home is the root ("/")
layouts/subscription_list
<ul>
<% current_user.subscriptions.each do |s| %>
<li><%= link_to s.url, "/?s_id=#{s.id}" %></li>
<% end %>
</ul>

Related

How to use Asset API to access liquid file through shopify_api gem ruby on rails

I am new to the shopify app development and I ran into the problem while accessing the template file for example : layout/theme.liquid using the shopify_api gem.
I actually am able to setup the gem properly in the app and deploy it correctly. I can access the products and webhooks and also the whole asset list. see my code :
Controller code
class HomeController < ShopifyApp::AuthenticatedController
def index
# below three access for product webhook and full asset are working fine
#products = ShopifyAPI::Product.find(:all, params: { limit: 10 })
#webhooks = ShopifyAPI::Webhook.find(:all)
#assets = ShopifyAPI::Asset.find(:all, params: {"theme_id": 194896516})
# not working below this line
#templates = ShopifyAPI::Asset.all(:params => {:theme_id=> 194896516}).find{|asset| asset.attributes[:key] == "layout/theme.liquid"}
end
end
Template that renders the value
<% content_for :javascript do %>
<script type="text/javascript">
ShopifyApp.ready(function(){
ShopifyApp.Bar.initialize({ title: "Home" });
});
</script>
<% end %>
<h2>Products</h2>
<ul>
<% #products.each do |product| %>
<li><%= link_to product.title, "https://#{#shop_session.url}/admin/products/#{product.id}", target: "_top" %></li>
<% end %>
</ul>
<hr>
<h2>Webhooks</h2>
<% if #webhooks.present? %>
<ul>
<% #webhooks.each do |webhook| %>
<li><%= webhook.topic %> : <%= webhook.address %></li>
<% end %>
</ul>
<% else %>
<p>This app has not created any webhooks for this Shop. Add webhooks to your ShopifyApp initializer if you need webhooks</p>
<% end %>
<hr>
<h2>Assets</h2>
<% if #assets.present? %>
<% #assets.each do |asset| %>
<li><%= asset.key %></li>
<!-- <li><% asset.value %></li> -->
<% end %>
<% else %>
<p>This app has not created any webhooks for this Shop. Add webhooks to your ShopifyApp initializer if you need webhooks</p>
<% end %>
<h2>Template</h2>
<% if #templates.present? %>
<% #templates.each do |template| %>
<li><%= template.key %></li>
<li><% template.value %></li>
<% end %>
<% else %>
<p>This app has not created any webhooks for this Shop. Add webhooks to your ShopifyApp initializer if you need webhooks</p>
<% end %>
I have also tried below variations on my controller but no luck
#templates = ShopifyAPI::Asset.find(:all, params: {"theme_id": 194896516, "asset[key]": 'layout/theme.liquid'})
Also
#templates = ShopifyAPI::Asset.find('layout/theme.liquid',params: {"theme_id": 194896516})
I have set the scope properly for read_themes. I checked the documentation and tried that too but couldn't succeed. Is there anything that I am missing or has the pattern changed over these years as the examples on documentation is not working.
The error I saw on the app is https://prnt.sc/jgglbf .
I hope anyone can help me with this. Really appreciate looking into this question.
Thanks

(Ruby on Rails) Displaying Posts Into Groups of 3

I'm using the following code to display posts to my users.
_feed.html.erb partial:
<% #posts_by_month.each do |monthname, posts| %>
<%= monthname %>
<ul>
<% posts.each do |post| %>
<li><%= post.created_at %></li>
<% end %>
</ul>
<% end %>
Controller:
def home
if logged_in?
#post = current_user.posts.build
#posts_by_month = current_user.feed.group_by { |post| post.created_at.strftime("%B") }
This renders my posts as follows:
Post 1
Post 2
Post 3
Post 4
I want to change it so that the posts are displayed like:
Post 1 Post 2 Post 3
Post 4 etc etc
etc
I've tried several approaches to this, including the in_groups_of(3) method however the way it is currently setup means nothing works. I feel like there is an obvious solution I'm missing - can anyone help?
[Edit to expand on the in_groups_of(3) error]
If I change line 4 in the _feed partial to:
<% posts.in_groups_of(3, false).each do |post| %>
It gives the error: undefined method `created_at' for #< Array:0xbb8f258 >
The #in_groups_of method returns an Array of Arrays each containing 3 Post objects.
So you now also need to iterate over the returned array that contains your three Posts, something like:
<% posts.in_groups_of(3, false).each do |post_group| %>
<% post_group.each do |post| %>
<li><%= post.created_at %></li>
<% end %>
<% end %>
You can use facets gem. This provides and each_by method. You can use each_by to create groups and iterate further on these groups.
Here is code snippet on how to use each_by
<div class = "small-9 columns vertical-border-left">
<%- #client.contact_details.each_by(3) do |contact_details| %>
<div class="row">
<%- contact_details.each do |contact| %>
<div class="small-3 columns small">
<div> <%= contact.contact_detail_type %> contact </div>
<div> <%= contact.contact_email %> </div>
<div> <%= contact.contact_phone %> </div>
</div>
<% end %>
</div>
<% end %>
</div>

undefined method 'each' when accessing articles from navbar in rails app

I need to be able to access articles through the navbar dropdown.
in my views/application/_navbar.html.erbI have the code snipped below. It is not working and I always get this error undefined method 'each' for nil:NilClass
when I hit the link in the dropdown the app goes to the right path http://localhost:3000/lcas/1
I only need to be able to access the first article in each category so http://localhost:3000/lcas/1 is the right path for the first link in the dropdown
code from views/application/_navbar.html.erb
<ul class="dropdown-menu">
<% #lcas.each do |lca| %>
<li><%= link_to lca.title, lca_path(lca) %></li>
<% end %>
<% #energy_analyses.each do |energy_analysis| %>
<li><%=link_to energy_analysis.title, energy_analysis_path(energy_analysis) %></li>
<% end %>
<% #green_accountings.each do |green_accounting| %>
<li><%= link_to green_accounting.title, green_accounting_path(green_accounting) %></li>
<% end %>
<li class="divider"></li>
<li>Something</li>
<li class="divider"></li>
<li>something</li>
</ul>
On my index.html.erbI have basically the same code and there it works.
<% #lcas.each do |lca| %>
<div class="col-md-4 col-xs-12">
<span class="glyphicon glyphicon-tasks icons" aria-hidden="true"> </span>
<div class="panel-heading">
<h3 class="panel-title"><%= link_to lca.title, lca_path(lca) %></h3>
</div>
</div>
<% end %>
I've tried to add
#lcas = Lca.all
#energy_analyses = EnergyAnalysis.all
#green_accountings = GreenAccounting.all
to the application_controller.rb but with out any success.
here is the lcas_controller.rb
class LcasController < InheritedResources::Base
private
def lca_params
params.require(:lca).permit(:title, :body, :image)
end
end
It would be very nice if someone could guide me through this.
You probably need few things:
Set a before_action method for those variables in application_controller.rb to make sure each other controller calls it and pass the variable to their corresponding view:
before_action :set_vars
def set_vars
#lcas = Lca.all
#energy_analyses = EnergyAnalysis.all
#green_accountings = GreenAccounting.all
end
Now you should be able to access #lcas from your partial, but using instance variables in partials is violating MVC, so you should pass locals to it:
<%= render 'application/navbar', :lcas => #lcas %>
Not sure how to pass multiple locals, maybe like this:
<%= render 'shared/navbar', locals: {:lcas => #lcas, :energy => #energy_analyses, :green => #green_accountings} %>
And of course, don't use # in partial if passing locals:
<% energy.each do |energy_analysis| %>

Render an attributes of each object - Rails

I have a view right now that renders an object on the page. The object is an Integration. On the Integration object I have attribute called filters. Filters are stored as an array. All I need to do is list out the filters of each integration below them in a list. Here is my code.
View
<% if #integrations.any? %>
<div class="configured-integrations">
<h3 class="heading-3">My Configured Integrations:</h3>
<ul class="integration-list integration-list--compact">
<%= render #integrations %>
</ul>
</div>
<% end %>
Screenshot
In the screenshot you can see that each of those elements are integrations. I need to list the filters of each integration below the title there.
Controller
def index
# Get the list of the user's integrations grouped first by provider then
# from oldest to newest."
#integrations = current_account.integrations
.order(type: :asc, created_at: :asc)
end
I hope this is clear enough. So recap: I need to list the filters on each integration below. I've already tried stuff like this #integrations.first.filters but that wont work because it's a static call. I need something like a list. Thank you
You can add another partial to render all filters which are associated with your Integration.
Create a partial file _show_filters.html.erb in your views
<% filters.each do |filter| %>
<li><%= filter %></li>
<% end %>
And render this partial while iterating through your #integration object like this.
<% if #integrations.any? %>
<div class="configured-integrations">
<h3 class="heading-3">My Configured Integrations:</h3>
<ul class="integration-list integration-list--compact">
<% #integrations.each do |integration| %>
<li>
<%= integration %>
<ul class="">
<%= render 'show_filters', filters: integration.filters %>
</ul>
</li>
<% end %>
</ul>
</div>
<% end %>
What you need to iterate through each integration, then <%= render integeration.filters %>
<% if #integrations.any? %>
<div class="configured-integrations">
<h3 class="heading-3">My Configured Integrations:</h3>
<ul class="integration-list integration-list--compact">
<% #integrations.each do |integration| %>
<li>
<%= integration %>
<ul class="">
<%= render integration.filters %>
</ul>
</li>
<% end %>
</ul>
</div>
<% end %>
You will have to update this code to make the partials work, but i hope this gets the idea across.
You can't use the shortcut <%= render #integrations %> here, because you want a subgroup inside #integrations. So you'll have to do it the long way.

How do I print validation messages for form_for :post structure?

I have something like
<div class="userInput">
<%= form_for :scribble do |f| %>
<%= f.text_area :scribble, cols: 65, rows: 4,:maxlength => 255%>
<%= f.submit %>
<% end %>
</div>
1)My Scribble model has min and max character length validation, now how do I print the error messages here. If it is an instance variable I know how to print, but this is a symbol.
2) This code is present in the application.html.erb. I am not able to understand how do I move it into a view of Scribble controller other than appliation. Problem is this form is not independent, it is a part of action index display of controller Scribbles,(and the form should be displayed always) and action index is already doing listing of scribbles.
Controller
def index
#scribbles = Scribble.order("scribbles.scribble DESC").all
end
def show
end
def new
end
def create
#scribble = Scribble.new(profile_params)
#scribble.likes =#scribble.dislikes =#scribble.shares=0;
#scribble.save
#scribbles = Scribble.order("scribbles.scribble DESC").all
render :index
end
Here how i out-put any errors or validation messages:
Controller:
def create
#scribble = Scribble.new(profile_params)
#scribble.likes =#scribble.dislikes =#scribble.shares=0;
if #scribble.save
flash[:notice] = "Scribble is successfully created"
redirect_to root_url
else #
render 'index'
end
end
Views:
Create a partial to show error messages if any e.g _error_messages.html.erb
<% if object.errors.any? %>
<div id="error_explanation">
<div class="alert callout text-center" data-closable>
<p><strong>This form contains <%= pluralize(object.errors.count, 'error') %>.</strong></p>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<button class="close-button" aria-label="Dismiss alert" type="button" data-close>
<span aria-hidden="true">×</span>
</button>
</div>
</div>
<% end %>
Render errors:
Now you can call <%= render 'layouts/error_messages', object: #scribble %> and put it anywhere in your views to render the errors validation. note: the object is passed, so it can be re-use to any form. credits to Hartl Tutorial.

Resources