rails partial doesn't receive variable - ruby-on-rails

My application has a Server and Domain modules such that server has_many domains and domain belongs_to server.
I'm trying to render a partial in the Server controller:
def get_domain_checkboxes
#domains = Domain.find_by(:server_id => params[:id])
render :partial => 'servers/domain_checkboxes', :layout => nil
end
The partial '_domain_checkboxes.html.erb' contains:
<% #domains.each do |domain| %>
domain.url
<% end %>
But I get an error when going to 'servers/3/get_domain_checkboxes' route and the trace says:
Started GET "/servers/3/get_domain_checkboxes" for ::1 at 2015-12-18 05:03:08 +0200
Processing by ServersController#get_domain_checkboxes as HTML
Parameters: {"server_id"=>"3"}
Domain Load (0.3ms) SELECT "domains".* FROM "domains" WHERE "domains"."server_id" IS NULL LIMIT 1
Rendered servers/_domain_checkboxes.html.erb (1.4ms)
Completed 500 Internal Server Error in 9ms (ActiveRecord: 0.4ms)
ActionView::Template::Error (undefined method `each' for nil:NilClass):
1: <% #domains.each do |domain| %>
2: hello
3: <% end %>
app/views/servers/_domain_checkboxes.html.erb:1:in `_app_views_servers__domain_checkboxes_html_erb___2806237560631891313_70206341448100'
app/controllers/servers_controller.rb:71:in `get_domain_checkboxes'
Tried anything for past hour. Probably something simple that I'm missing?
EDIT:
Tried #domains = Domain.find_by(:server_id => params[:server_id]) instead but still get an error:
Started GET "/servers/3/get_domain_checkboxes" for ::1 at 2015-12-18 05:09:43 +0200
Processing by ServersController#get_domain_checkboxes as HTML
Parameters: {"server_id"=>"3"}
Domain Load (0.1ms) SELECT "domains".* FROM "domains" WHERE "domains"."server_id" = ? LIMIT 1 [["server_id", 3]]
Rendered servers/_domain_checkboxes.html.erb (1.6ms)
Completed 500 Internal Server Error in 3ms (ActiveRecord: 0.1ms)
ActionView::Template::Error (undefined method `each' for #<Domain:0x007fb465810738>):
1: <% #domains.each do |domain| %>
2: hello
3: <% end %>
app/views/servers/_domain_checkboxes.html.erb:1:in `_app_views_servers__domain_checkboxes_html_erb___2806237560631891313_70206341448100'
app/controllers/servers_controller.rb:71:in `get_domain_checkboxes'

You need to change:
#domains = Domain.find_by(:server_id => params[:id])
to
#domains = Domain.where(:server_id => params[:server_id])

Related

Back Button Skipping Page in Ruby on Rails application

I have found many generic posts suggesting this has to do with redirects. I believe this may be due to how I have a form set up.
On the plans.html.erb page I have a form with four submits, each going to the same place with different params:
<%= form_with url: :affiliate_select_plan, class: "mx-auto" do |f| %>
<!-- Paid Plans -->
<% #plans.each_with_index do |plan, i| %>
<%= f.button 'Select Plan', value: plan[:name], type: 'submit' %>
<% end %>
<% end %>
I have the affiliate_select_plan_path setup in my routes.rb:
devise_scope :affiliate do
post 'affiliate/select_plan', :to => 'affiliates/registrations#select_plan'
end
The form successfully hits the select_plan method in the controller, which redirects it to the new_affiliate_registration_path, passing the needed params.
def select_plan
redirect_to new_affiliate_registration_path(plan: plan_params[:button])
end
The new method in the controller is called, directing the user to the sign up page:
# GET /resource/sign_up
def new
#plan = AffiliatePlan.find_by(nickname: params.permit(:plan)[:plan].downcase)
super
end
From this page, if the back button on the browser is selected, it will bring the user back to the page they were at before being at plans.html.erb.
Could this be related to the redirect_to?
EDIT:
Here are the logs:
Started GET "/" for 127.0.0.1 at 2020-02-25 19:06:02 -0500
Processing by Affiliates::RegistrationsController#plans as HTML
Rendering affiliates/registrations/plans.html.erb within layouts/application
Rendered affiliates/registrations/plans.html.erb within layouts/application (5.2ms)
Rendered layouts/_google_analytics.html.erb (0.5ms)
[Webpacker] Everything's up-to-date. Nothing to do
Rendered layouts/_header.html.erb (1.2ms)
Rendered layouts/_footer.html.erb (0.7ms)
Completed 200 OK in 195ms (Views: 194.2ms | ActiveRecord: 0.0ms)
Started POST "/partner/select_plan" for 127.0.0.1 at 2020-02-25 19:06:13 -0500
Processing by Affiliates::RegistrationsController#select_plan as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Ck8HGRryriXleQrUjCSKjTrIRLIw273EdSu4WZnFn3kAL1mMmk7jqR1tZgnPniHsMzHFMl81vPBRuvA0/W4uSw==", "button"=>"Local"}
Unpermitted parameters: :utf8, :authenticity_token
Redirected to http://localhost:3000/partners/sign_up?plan=Local
Completed 200 OK in 1ms (ActiveRecord: 0.0ms)
Started GET "/partners/sign_up?plan=Local" for 127.0.0.1 at 2020-02-25 19:06:13 -0500
Processing by Affiliates::RegistrationsController#new as HTML
Parameters: {"plan"=>"Local"}
AffiliatePlan Load (1.2ms) SELECT "affiliate_plans".* FROM "affiliate_plans" WHERE "affiliate_plans"."nickname" = $1 LIMIT $2 [["nickname", "local"], ["LIMIT", 1]]
↳ app/controllers/affiliates/registrations_controller.rb:11
Rendering affiliates/registrations/new.html.erb within layouts/application
Rendered affiliates/registrations/new.html.erb within layouts/application (4.6ms)
Rendered layouts/_google_analytics.html.erb (1.1ms)
[Webpacker] Everything's up-to-date. Nothing to do
Rendered layouts/_header.html.erb (1.2ms)
Rendered layouts/_footer.html.erb (0.7ms)
Completed 200 OK in 191ms (Views: 187.6ms | ActiveRecord: 1.2ms)
I have a hunch that this might have to do with form resubmission: Forms and the back button tend to be a bit wonky at times.
However, instead of going more in depth with this, let me point you in another direction. I'm doing this because to me, this looks like a classic case of someone trying to find a solution to the wrong problem. I'm saying this because based on the code and log snippets you've provided, you're jumping through hoops to pass a parameter (in your case the name of a plan) via multiple actions – which, if I'm right, is just unnecessary.
Here's what I would do instead:
<% #plans.each do |plan| %>
<%=
link_to 'Select Plan',
new_affiliate_registration_path(plan: plan.downcase),
class: 'some-button-class
%>
<% end %>
This way, you don't have to mess around in your controllers in any way. Also, since there is no POST request, you won't have any issues with form (re)population and such things.

undefined method `user' for nil:NilClass in Ruby Tokbox API

i am trying to use the tokbox api and have the following error:
Started GET "/en/stream" for 127.0.0.1 at 2018-06-02 18:38:57 +0800
Processing by UsersController#stream as HTML
Parameters: {"locale"=>"en"}
Rendering users/stream.html.erb within layouts/application
Rendered users/stream.html.erb within layouts/application (3.8ms)
Completed 500 Internal Server Error in 34ms (ActiveRecord: 0.3ms)
ActionView::Template::Error (undefined method `user' for nil:NilClass):
1: <%= javascript_include_tag "//static.opentok.com/webrtc/v2.2/js/TB.min.js" %>
2: <h1>Your stream</h1>
3: <div id="publisher"></div>
4: Link to your stream: <%= link_to watch_url(#stream.user.id), watch_url(#stream.user.id) %>
app/views/users/stream.html.erb:4:in `_app_views_users_stream_html_erb__3447765015494674598_70186549432640'
My User/stream.html.erb looks like:
<%= javascript_include_tag "//static.opentok.com/webrtc/v2.2/js/TB.min.js" %>
<h1>Your stream</h1>
<div id="publisher"></div>
Link to your stream: <%= link_to watch_url(#stream.user.id), watch_url(#stream.user.id) %>
My UserController looks like :
def stream
#stream = User.find(params[:id]).stream
#stream = current_user.stream || current_user.create_stream
gon.opentok = opentok_data(#stream)
end
def watch
#stream = User.find(params[:id]).stream
gon.opentok = opentok_data(#stream)
end
private
def opentok_data(stream)
token = OpenTokClient.generate_token(stream.opentok_session_id)
{ sessionId: stream.opentok_session_id, apiKey: Figaro.env.opentok_api_key, token: token }
end
My user model has one stream, and my stream model has one user.
Does anyone knows why it is not recognising the user ?

Error validating signup form using tableless implementation

I'm trying to implement a signup form. See this screenshot. I'm using the LearnRails tutorial to help me.
It works when you type in a valid email address. However, if you don't type in a valid email address, it's giving me this error: undefined method 'empty?' for nil:NilClass. My logs say this:
ActionView::Template::Error (undefined method `name' for nil:NilClass):
1: <% content_for(:title, "#{#college.name} Student Reviews" + " | #{params[:section1]} | #{params[:section2]}".titleize) %>
2: <% description "#{#question}" %>
3:
4: <div id="college_pages_css">
app/views/college_pages/disqus_normal.html.erb:1:in `_app_views_college_pages_disqus_normal_html_erb___3963356040782610986_70269489097160'
Which is weird because it should be redirecting to my home page, which doesn't have the #college variable.
Note: I'm using the activerecord-tableless gem, because the tutorial uses it.
Model
class Subscriber < ActiveRecord::Base
attr_accessible :email
has_no_table
column :email, :string
validates_presence_of :email
validates_format_of :email,
:with => /\A[-a-z0-9_+\.]+\#([-a-z0-9]+\.)+[a-z0-9]{2,4}\z/i
def subscribe
mailchimp = Gibbon::API.new(ENV['MAILCHIMP_API_KEY'])
result = mailchimp.lists.subscribe({
:id => ENV['MAILCHIMP_LIST_ID'],
:email => {:email => self.email},
:double_optin => false,
:update_existing => true,
:send_welcome => true
})
Rails.logger.info("Subscribed #{self.email} to MailChimp") if result
end
end
Controller
class SubscriberController < ApplicationController
def create
#subscriber = Subscriber.new(params[:subscribe])
if #subscriber.valid?
#subscriber.subscribe
redirect_to root_path
else
render root_path
end
end
end
View
<%= simple_form_for :subscribe, url: 'subscribe' do |f| %>
<%= f.input :email, label: false %> <br/>
<%= f.button :submit, "Notify me", class: "btn btn-primary" %>
<% end %>
Note that the tutorial uses a secure_params method while I'm using attr_accessible. I wouldn't think that this would be a problem, but it's possible.
I was thinking of ignoring this issue, and just using client side validations, but that causes my site to crash. On the topic of client side validations, aren't HTML5 email input fields supposed to automatically validate?
How can I fix this issue?
Edit: Logs when I load the home page
Started GET "/" for 127.0.0.1 at 2014-04-01 16:15:47 -0400
Processing by StaticPagesController#home as HTML
Rendered static_pages/home.html.erb within layouts/application (3.6ms)
Completed 200 OK in 41ms (Views: 40.3ms | ActiveRecord: 0.0ms)
Started GET "/assets/jquery.ui.theme.css?body=1" for 127.0.0.1 at 2014-04-01 16:15:47 -0400
Started GET "/assets/jquery.ui.accordion.css?body=1" for 127.0.0.1 at 2014-04-01 16:15:47 -0400
.
.
.
Started GET "/favicon.ico" for 127.0.0.1 at 2014-04-01 16:15:49 -0400
Started GET "/favicon/academics/professors/1" for 127.0.0.1 at 2014-04-01 16:15:50 -0400
Processing by CollegePagesController#disqus_normal as */*
Parameters: {"college"=>"favicon", "section1"=>"academics", "section2"=>"professors", "question_id"=>"1"}
College Load (1.4ms) SELECT "colleges".* FROM "colleges" WHERE "colleges"."url" = 'favicon' LIMIT 1
Rendered college_pages/disqus_normal.html.erb within layouts/application (3.7ms)
Completed 500 Internal Server Error in 14ms
ActionView::Template::Error (undefined method `name' for nil:NilClass):
1: <% content_for(:title, "#{#college.name} Student Reviews" + " | #{params[:section1]} | #{params[:section2]}".titleize) %>
2: <% description "#{#question}" %>
3:
4: <div id="college_pages_css">
app/views/college_pages/disqus_normal.html.erb:1:in `_app_views_college_pages_disqus_normal_html_erb___3963356040782610986_70269489097160'
Rendered /Users/adamzerner/.rvm/gems/ruby-2.0.0-p451#global/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.erb (80.6ms)
Rendered /Users/adamzerner/.rvm/gems/ruby-2.0.0-p451#global/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.6ms)
Rendered /Users/adamzerner/.rvm/gems/ruby-2.0.0-p451#global/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (98.3ms)
Started GET "/assets/favicon.ico" for 127.0.0.1 at 2014-04-01 16:15:50 -0400
disqus_normal action
def disqus_normal
#college = College.find_by_url(params[:college])
#question = get_question(params[:section2], params[:question_id])
end
The error
undefined method 'name' for nil:NilClass
is appearing on line 1 which is
<% content_for(:title, "#{#college.name} Student Reviews" + " | #{params[:section1]} | #{params[:section2]}".titleize) %>
of college_pages/disqus_normal.html.erb page.
It means that #college is nil and you are trying to access property name on a nil object. Hence, the error.
To resolve this make sure that you set the value of #college instance variable in the action from where you are redirecting to this page.
UPDATE
Also, there was an issue with routing.
get '/:college', to: redirect('/%{college}/academics/professors/1')
Because of the above problematic route GET "/favicon.ico" is getting converted to GET "/favicon/academics/professors/1" and disqus_normal is getting called. Ideally it would be better if you add some static text to the problematic route.
For example:
get '/college/:college', to: redirect('/%{college}/academics/professors/1')

Dont understand why I'm encountering this TypeError (Can't convert nil into String)

Very simple process I'm trying to implement.
On a home page or landing page I want to capture emails for an email list.
If the email passes validation, it gets saved, Great! Everything works fine when there are no errors.
When there is an error like only inputting an 'a' character as shown in the log below. Or even just an empty string I continually get the same TypeError (can't convert nil to String)
Here is the log:
Started GET "/" for 127.0.0.1 at 2013-06-13 13:48:56 -0400
Connecting to database specified by database.yml
Processing by HighVoltage::PagesController#show as HTML
Parameters: {"id"=>"home"}
Rendered shared/_error_messages.html.erb (0.4ms)
Rendered layouts/_visitor_form.html.erb (7.9ms)
Rendered pages/home.html.erb within layouts/application (13.1ms)
Completed 200 OK in 82ms (Views: 39.6ms | ActiveRecord: 1.8ms)
[2013-06-13 13:48:57] WARN Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
Started POST "/visitors" for 127.0.0.1 at 2013-06-13 13:48:59 -0400
Processing by VisitorsController#create as HTML
Parameters: {"utf8"=>"✓",authenticity_token"=>"esTPNzNtkmNPTe7Jh+E2aDHNrgocU5Z8g49Nj0QiOhQ=", "visitor"=>{"email"=>""}, "commit"=>"Add to newsletter list"}
(0.1ms) begin transaction
Visitor Exists (0.2ms) SELECT 1 AS one FROM "visitors" WHERE LOWER("visitors"."email") = LOWER('') LIMIT 1
(0.1ms) rollback transaction
Completed 500 Internal Server Error in 39ms
TypeError (can't convert nil into String):
app/controllers/visitors_controller.rb:12:in `create'
Here is the visitors_controller.rb
def create
#visitor = Visitor.new(params[:visitor])
if #visitor.save
flash[:success] = "Your email has been added!"
redirect_to '/'
else
render '/'
end
end
I've also tried
#visitor = Visitor.new(:visitor => params[:visitor][:email])
and a few other sequences with no success.
How can I get the unsuccessful saves to gracefully show the validation errors and allow the user to resubmit.
Here is the layout:
<%= form_for Visitor.new do |f| %>
<%= render 'shared/error_messages' %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.submit "Add to newsletter list", class: "btn btn-large btn-primary" %>
<% end %>
Maybe the high_voltage gem is screwing me up. I don't have enough experience to know.
UPDATE:
rake routes
visitors POST /visitors(.:format) visitors#create
home /home(.:format) pages#home
root / high_voltage/pages#show {:id=>"home"}
page GET /pages/*id high_voltage/pages#show
The problem is, render '/' does not render index page. You have to specify which action page you want to be rendered. According to your routes, this line should look like this:
render 'pages/home'

Routing problem in rails

// see below for update
Error:
No route matches {:controller=>"conversations", :action=>"reply", :id=>nil, :board_id=>nil}
Parameters dump:
{"board_id"=>"2",
"id"=>"3"}
Log:
Started GET "/boards/2/conversations/3/reply" for 127.0.0.1 at Mon Apr 04 23:40:59 +0200 2011
Processing by ConversationsController#reply as HTML
Parameters: {"board_id"=>"2", "id"=>"3"}
Board Load (0.1ms) SELECT "boards"."id" FROM "boards" WHERE ("boards"."id" = 2) LIMIT 1
Board Load (0.6ms) SELECT "boards".* FROM "boards" WHERE ("boards"."id" = 2) LIMIT 1
Rendered conversations/_reply_form.html.erb (1.3ms)
Rendered conversations/reply.html.erb within layouts/application (9.4ms)
Completed in 30ms
ActionView::Template::Error (No route matches {:controller=>"conversations", :action=>"reply", :id=>nil, :board_id=>nil}):
1: <%= form_for(#comment, :url => reply_board_conversation_url(:board_id=>#board_id, :id=>#conversation_id)) do |f| %>
2: <% if #comment.errors.any? %>
3: <div id="error_explanation">
4: <h2><%= pluralize(#comment.errors.count, "error") %> prohibited this reply from being saved:</h2>
app/views/conversations/_reply_form.html.erb:1:in `_app_views_conversations__reply_form_html_erb__999049254_2171331720_2303070'
app/views/conversations/reply.html.erb:4:in `_app_views_conversations_reply_html_erb___838091718_2171408600_0'
Rendered /opt/local/lib/ruby/gems/1.8/gems/actionpack-3.0.0/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.1ms)
Rendered /opt/local/lib/ruby/gems/1.8/gems/actionpack-3.0.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (982.1ms)
Rendered /opt/local/lib/ruby/gems/1.8/gems/actionpack-3.0.0/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (1001.7ms)
In my routes.rb, its:
get '/boards/:board_id/conversations/:id/reply' => "conversations#reply", :as => :reply_board_conversation
post '/boards/:board_id/conversations/:id/reply' => "conversations#save_reply", :as => :reply_board_conversation
resources :boards do
resources :conversations
end
Does anyone know what I'm doing wrong? Thanks in advance!
// Update:
Figured out the params. But, now we have a new error.. see output:
Started GET "/boards/2/conversations/3/reply" for 127.0.0.1 at Tue Apr 05 11:29:52 +0200 2011
Processing by ConversationsController#reply as HTML
Parameters: {"board_id"=>"2", "conversation_id"=>"3"}
Board Load (0.2ms) SELECT "boards"."id" FROM "boards" WHERE ("boards"."id" = 2) LIMIT 1
Board Load (0.2ms) SELECT "boards".* FROM "boards" WHERE ("boards"."id" = 2) LIMIT 1
Rendered conversations/_reply_form.html.erb (4.3ms)
Rendered conversations/reply.html.erb within layouts/application (6.3ms)
Completed in 26ms
ActionView::Template::Error (undefined method `model_name' for NilClass:Class):
1: <%= form_for(#comment, :url => reply_board_conversation_url(:board_id=>#board.id, :id=>#conversation_id)) do |f| %>
2: <% if #comment.errors.any? %>
3: <div id="error_explanation">
4: <h2><%= pluralize(#comment.errors.count, "error") %> prohibited this reply from being saved:</h2>
app/views/conversations/_reply_form.html.erb:1:in `_app_views_conversations__reply_form_html_erb__999049254_2174448800_2303070'
app/views/conversations/reply.html.erb:1:in `_app_views_conversations_reply_html_erb___838091718_2174498080_0'
Rendered /opt/local/lib/ruby/gems/1.8/gems/actionpack-3.0.0/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.1ms)
Rendered /opt/local/lib/ruby/gems/1.8/gems/actionpack-3.0.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (757.4ms)
Rendered /opt/local/lib/ruby/gems/1.8/gems/actionpack-3.0.0/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (774.2ms)
The log you provided indicates the #board_id and #conversation_id variables are nil.
Make sure you are actually setting the value of #board_id and #conversation_id in ConversationsController's reply action. I suspect you are either populating board_id or forgetting to do something like #board_id = params[:board_id] altogether.
Update
To answer the next part of your question, I am guessing that #comment has not been instantiated. Somewhere in your controller action you should do something like the following:
#comment = Comment.new(params[:comment]
This should create a comment from any existing form data, or a new comment if there isn't any form data.
Your #board_id and #conversation_id variables are both nil, as it says in the error message:
No route matches {:controller=>"conversations",
:action=>"reply",
:id=>nil,
:board_id=>nil
}
Note the :id and :board_id parameters here.

Resources