#meditations.count works within folder but not in partial used elsewhere - ruby-on-rails-4

views/meditations/_count.html.erb
<p><small><%= #meditations.count %></small></p>
when I try using that on the home page like so:
<%= render partial: "/meditations/count" %>
I get the error:
undefined method `count' for nil:NilClass
I tried to change the call to:
<%= render partial: "/meditations/count", object: #meditations %>
I finally got what I wanted but I'm thinking I violated some kind of law by doing this on the home page:
<p><%= Meditations.count %> </p>
What should I have done to get the partial working?

I get the error:
undefined method `count' for nil:NilClass
Any time you see undefined ____ for nil class it is b/c you are calling blah on something that you think has value, but is nil. In other words, #mediatations is coming in as nil.
So check your controller. In the method that matches this page, make sure you have something like #meditations = Meditation.all.
Lastly, yes - Meditations.count is a call to the db from the view. Very bad practice. Basically breaking MVC.

Related

Rails 4 not changing post method to patch

I am trying to submit a form, but if I just put form_for #classroom I get a "No route matches [POST]" error.
Now with the code posted below, I get the wrong url in the form. If I change the url manually in the browser it goes through, and I guess I could do that via javascript, but... why... is... this... happening..?
Until yesterday everything was working fine. I even tried rolling back to the things I changed but I can't seem to track what is going wrong.
routes.rb
patch 'classrooms/:id/update' => "classrooms#update", as: :update_classroom
resources :classrooms, except: :update
form from rails end
<%= form_for(update_classroom_path(#classroom), method: "patch") do |class_f| %>
form in browser
<form action="/classrooms/23/edit" accept-charset="UTF-8" method="post">
<input name="utf8" type="hidden" value="✓">
<input type="hidden" name="_method" value="patch">
<input type="hidden" name="authenticity_token" value="******">
rake routes
absences POST /absences(.:format) absences#create
POST /classrooms/:id/getAbsences(.:format) classrooms#getAbsences
update_classroom PATCH /classrooms/:id/update(.:format) classrooms#update
classrooms GET /classrooms(.:format) classrooms#index
POST /classrooms(.:format) classrooms#create
new_classroom GET /classrooms/new(.:format) classrooms#new
edit_classroom GET /classrooms/:id/edit(.:format) classrooms#edit
classroom GET /classrooms/:id(.:format) classrooms#show
DELETE /classrooms/:id(.:format) classrooms#destroy
root GET / pages#start
Just to answer your question from title, I think your form method is "PATCH" indeed. Refer to the guide http://guides.rubyonrails.org/form_helpers.html about how rails makes a patch form.
The Rails framework encourages RESTful design of your applications, which means you'll be making a lot of "PATCH" and "DELETE" requests (besides "GET" and "POST"). However, most browsers don't support methods other than "GET" and "POST" when it comes to submitting forms.
Rails works around this issue by emulating other methods over POST with a hidden input named "_method", which is set to reflect the desired method:
To add a bit of specificity, to Tashow's answer above (which set me on the right track), I had some hidden fields that look'd like this, in a nested form.:
<%= hidden_field_tag("Classroom[classroom_teachers_attributes][]", nil) %>
<%= hidden_field_tag("Classroom[classroom_teachers_attributes][]", '') %>
Once I got rid of these, everything began working properly again. (There still remained similar-looking <input> tags generated by fields_for, etc.)
After some more trial and error, I realised I had left some plain input tags in a deeper nested level of the form (instead of going with the normal fields_for and separate builders for each level). I guess that somehow screwed up the relations and affected the method of the parent form.
That was such a mind blending mess up.
Edit: Andylee's answer is right. What I and Jeremy mention was probably the actual issue going on and not what was originally assumed to be the problem (as mentioned in the title).
form_for takes an object as first argument, and its usually better to keep the REST-like way of rails handling the update method.
The action of you html form displays "/classrooms/23/edit" so yes it won't work.
form_for(#classroom, url: update_classroom_path(#classroom), method: "patch")

Getting same style in another page when click to login

I am having a login page for user generated by devise gem.where I removed the registerable from model for only login not for signup.I have also generated an admin which gives default login credentials for user in seed.rb file.I have done some css work in login page. next I have generated an employee page for further process for users.
Here my doubt is the styling part what I have done in login page is also coming in employee page. I dont want that so I wrote some condition in application.html.erb
<% unless user_signed_in? %>
<%= render 'layouts/heading' %>
<% end %>
The method is defined in application.controller.rb
def user_signed_in? %>
render :layouts => 'application'
end
I tried a lot by changing conditions but it is still displaying or showing errors.
You said that you're using "device gem", but since you're talking about authentication, I assume you mean "devise"?
The user_signed_in? method is a helper which should be provided automatically by devise, and you should be able to use it in your views. You shouldn't need to define it in the application controller.
You probably want to make sure you do "before_filter :authenticate_user!" in the relevant controller (you can use the ":only" option if you only want this to apply for certain methods).
It's difficult to give any more information because you haven't said what errors you are getting. I assume you're getting some kind of syntax error on the definition of the "user_signed_in?" method, since you have an invalid "%>"on the end of the line, which I guess you copied-and-pasted from an ERB file.

Rails: How to check for attributes with polymorphic? (Prints okay, won't allow conditional)

Going back to accessing user attributes (name, e-mail, avatar, etc) for the comments section ("identify user as commenter"), why does it let me print out some values but not use them in conditionals?
Why can I do this? (Prints the avatar next to the comment as it should)
<%= image_tag comment.user.avatar.url, size: "64" %>
But not this? (Won't let me check if there's an avatar or not first)
<% if comment.user.avatar.url.empty/blank/nil/present? %>
So if a commenter hasn't uploaded an avatar yet, it returns:
undefined method \'avatar\' for nil:NilClass
Is there a method I need to define in a controller, or a scope in a model, or is there another way of checking in this situation?
Thank you.

url_for in an email sent by a rake task in rails 4

I have a rake task that sends out daily digest emails of player activity during a day. (See example code below.) If I run PlayerActivityMailer.activity_report.deliver in my console, everything works just fine. However, when I try to invoke the rake task, I get the following error:
rake aborted!
ActionView::Template::Error: arguments passed to url_for can't be handled.
Please require routes or provide your own implementation
After doing some research, I found that in Rails 4, they totally nerfed ActionView::Helpers::UrlHelper.url_for (http://apidock.com/rails/v4.1.8/ActionView/Helpers/UrlHelper/url_for - notice the giant red minus sign under the 4.0.2). If you look at the source, you can see the error I'm seeing - it no longer takes options. As far as I can tell, that functionality still exists in other url_fors, such as the one in ActionDispatch::Routing::UrlFor. Also, the error message suggests including Rails.application.routes.url_helpers.
What I've tried
include ActionDispatch::Routing::UrlFor in both the rake task (inside the task) and the mailer (both at the same time, and each separately)
include Rails.application.routes.url_helpers in the same places and configurations, both with and without the UrlFor include.
The error still persists. My guess is that the page view is still insisting on using the ActionView::Helpers::UrlHelper version of url_for. I don't think I can include things actually in the views (which is sloppy looking and hacky even if I could).
Example Code
(heavily sanitized)
config/environtments/development.rb:
config.action_mailer.default_url_options = { host: 'localhost:3000' }
lib/tasks/player.rake:
namespace :player do
task :activity => :environment do
PlayerActivityMailer.activity_report.deliver
end
end
app/mailers/player_activity_mailer.rb:
class PlayerActivityMailer < ActionMailer::Base
def activity_report
#activities = PlayerActivity.all
mail(to: 'foo#bar.com', subject: 'activity report')
end
end
app/views/player_activity_mailer/activity_report.html.erb:
<% #activites.each do |activity| %>
Player: <%= link_to activity.player.name, player_url(id: activity.player.id) %>
...
<% end %>
I also have a model Player, resources :players in my routes.rb file, and a PlayerActivity class with an association to Player.
I'm currently using the (really horrifying) workaround of #base_url = Rails.configuration.action_mailer.default_url_options[:host] in my mailer action and "http://#{#base_url}/players/#{activity.player.id}" in my view instead of the player_url part.
Help!
Have you tried passing just your player in the URL? Like this:
<% #activites.each do |activity| %>
Player: <%= link_to activity.player.name, player_url(activity.player) %>
<% end %>

Inserting a variable argument into a Silverstripe template's function?

I'm using a pagination example from balbus design. In the .ss template, there is a line of code:
<% control ProductList.PaginationSummary(5) %>
Is that possible to use a variable instead of hard-coding the value 5? For example:
<% control ProductList.PaginationSummary(PSSize) %>
The variable PSSize is defined in the model and will return the number set in the CMS.
The SS 2.4 templating language is very limited in terms of what it can do.
In this specific case, you could try working it out in the controller - try adjusting the $resultSet within ProductListPage_Controller::ProductList to preprocess the pagination summary to desired context size, so you can access it later from the template.
Try something like that:
$resultSet->AdjustedPaginationSummary = $resultSet->PaginationSummary($this->productsPerPage);
return $resultSet;
And then in the template you should be able to do:
<% control ProductList.AdjustedPaginationSummary %>