View:-
<% #dating_advices.each do |da| %>
<% if da['is-displayed'][0]['content'] == 'true' %>
<div class="dating_advice">
<h4><%= da['title'][0] %></h4>
<p><b><%= da['author'][0] %></b></p>
<p><%= da['content'] %></p>
</div>
<hr>
<% end %>
<% end %>
Controller:-
def dating_advices
#current_menu = "MatchMasters"
logger.debug "*** Current site id: #{#current_site.id}"
##hide_quick_search = true
#passed_args = {
'event_action' => 'ws',
'site_id' => #current_site.site_id
}
result = call_dating_advices_ws(#passed_args)
if result && result['errorcode'][0] == 'success'
#dating_advices = result['payload'][0]['payload']
end
end
Now when I click on dating advices on my webpage it gives an error"Getting Template::Error (Undefined method 'each') for nil:NIL Class"
You probably didn't get any #dating_advices -- which would mean you're calling each on an instance var that doesn't exist.
The way your controller is written, #dating_advices is never defined if the result variable is not defined.
You could quickly patch it with a #dataing_advices = [] (or a hash -- anything with an .each method) and figure out why your controller is failing.
You could do something like
if result && result['errorcode'][0] == 'success'
... your dating advice code
else
raise result
(or #dating_advice = {})
end
basically you need to always defined #dating_advice OR you need to handle that value not being defined in your view.
Related
Guess
it's strange that it certainly occurs when there is no record in the database.
What I tried
I doubted that the cause was actually ajax so I all removed remote:true but it hardly worked.
controller
def create
#sell = current_user.orders.build(sell_params)
#buy = current_user.orders.build(buy_params)
if #sell.save
flash[:success] = 'your order has successfully submitted.'
notify_order(#sell.rate, #sell.amount, #sell.order_type)
#sell.rate.present? ? #sell.update(order_type: 'limit_sell') : #sell.update(order_type: 'market_sell')
fund = Fund.create_with(amount: 0, crypto_address_id: 1)
.find_or_create_by(user_id: current_user.id, kind: #sell.pair.split('_').last)
fund.update(in_use: #sell.rate * #sell.amount) if #sell.order_type == 'limit_sell'
# try to make orders done
market_checker(#sell.pair)
else
if Order.where(order_status: 'done', pair: params[:order][:pair]).present?
#currency_price = Sell.where(trading_status: 'done', currency_id: Currency.find_by_slug(params[:sell][:currency_id]).id)
#currency_price.present? ? #currency_price = #currency_price.last.price : #currency_price = ''
else
flash[:danger] = "Unfortunately, there is no trading right now so that we can't show you the chart"
end
#pair = params[:order][:pair].to_s
render :new
end
if #buy.save
flash[:success] = 'your order has successfully submitted.'
notify_order(#buy.rate, #buy.amount, #buy.order_type)
#buy.rate.present? ? #buy.update(order_type: 'limit_buy') : #buy.update(order_type: 'market_buy')
fund = Fund.create_with(amount: 0, crypto_address_id: 1).find_or_create_by(user_id: current_user.id, kind: #buy.pair.split('_').last)
fund.update(in_use: #buy.rate * #buy.amount) if #buy.order_type == 'limit_buy'
# try to make orders done
market_checker(#buy.pair)
else
if Order.where(order_status: 'done', pair: params[:order][:pair]).present?
#currency_price = Sell.where(trading_status: 'done', currency_id: Currency.find_by_slug(params[:sell][:currency_id]).id)
#currency_price.present? ? #currency_price = #currency_price.last.price : #currency_price = ''
else
flash[:danger] = "Unfortunately, there is no trading right now so that we can't show you the chart"
end
#pair = params[:order][:pair].to_s
render :new
end
end
model
class Order < ApplicationRecord
belongs_to :user
validate :deposited_btc_enough?
validate :insufficient?
validates :amount, format: { with: /\A\d+(?:\.\d{0,8})?\z/ }, numericality: { greater_than: 0.000000009, less_than: 100_000_000 }, presence: true
validate :rate_check
validates :rate, format: { with: /\A\d+(?:\.\d{0,8})?\z/ }, numericality: { greater_than: 0.000000009, less_than: 100_000_000 }, if: :rate_present?
validate :checking_order_type
def rate_present?
rate.present?
end
def checking_order_type
if order_type == 'sell_limit' || order_type == 'buy_limit'
errors.add(:Please, 'specify the rate of your order.') unless rate.present?
end
if order_type == 'sell_market' || order_type == 'buy_market'
errors.add(:You, "can't specify the rate of your order.") if rate.present?
end
end
def deposited_btc_enough?
if rate.present?
if rate.to_d > '0'.to_d && amount > 0
deposited_amount = user.fund.amount if user.fund.amount.present?
amount = rate.to_d * amount.to_s.to_d
if deposited_amount.present?
if coin_to_satoshi(amount).to_i > coin_to_satoshi(deposited_amount).to_i
errors.add(:Your, 'deposited yen is short to order.')
end
else
errors.add(:You, "haven't deposited yen yet or Your transaction hasn't confirmed yet.")
end
else
errors.add(:You, "can't specify negative numbers here.")
end
end
end
def to_param
uuid
end
def insufficient?
if amount.present? && order_type.split('_').last == 'sell'
if CurrencyUser.find_by(user_id: user.id, currency_id: Pair.find_by(name: pair).currency_id).amount < amount
errors.add(:amount, 'of this order is more than your holdings.')
errors[:base] << 'Errors that are related to this order exist.'
end
end
end
def is_number?(string)
true if Float(string)
rescue StandardError
false
end
def rate_check
if rate.present?
errors.add(:You, 'can only specify numbers') unless is_number?(rate)
errors.add(:You, "can't specify the rate as a negative number.") unless '0'.to_d < rate.to_d
end
end
end
form
<%= form_for(#sell,remote:true) do |f| %>
<% if #sell.errors.any? %>
<div id="error_explanation" class="alert alert-danger">
<h2><%= #sell.errors.count %>error(s) exist(s).</h2>
<ul>
<% #sell.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.hidden_field :pair,value:#pair%>
<%= f.hidden_field :order_type,value:"market_sell"%>
<p>amount whatever you want to sell like 100</p>
<div class="input-group">
<%= f.number_field :amount, class: 'form-control form-group',placeholder:"amount"%>
</div>
<%= f.submit 'done', class: "btn btn-large bg-info" %>
<% end %><br>
<%= form_for(#buy,remote:true)do |f| %>
<% if #buy.errors.any? %>
<div id="error_explanation" class="alert alert-danger">
<h2><%= #buy.errors.count %>error(s) exist(s).</h2>
<ul>
<% #buy.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
Thanks
Your create method has way too much complexity and I'm assuming you have not written this method with test driven development because you would have broken it down into smaller methods if you had, likely moving more of the logic to the model. I also hope this is not how your code style looks in real life. At first glance, I'm assuming your problem is this:
def create
# why are you creating 2 orders?? Can you change this:
#sell=current_user.orders.build(sell_params)
#buy=current_user.orders.build(buy_params)
#to something more like:
#order = order_from_params
#...omitting rest of this code because it needs a lot of refactoring.
end
private
def order_from_params
#you should probably only deal with 1 order at a time either buy or sell
# you must have a field in orders table to indicate buy or sell, probably int?
if sell_params.present?
#order = current_user.orders.build(sell_params)
else
#order = current_user.orders.build(buy_params)
end
end
Then you'll need to simplify the logic in create method since you only have one model to deal with. You should NOT rely on nor do 2 if #order.save inside the create action since you should again only be creating 1 order at a time. This should get you headed in the right direction. And if you're not doing test driven development, you're gonna have a lot worse problems then what you have already.
Having a bit of a rough time on this example, my code reads as:
view
<% monthNumber = (Time.now - 1.month).strftime("%m") #
yearNumber = (Time.now).strftime("%Y") #
monthWord = (Time.now - 1.month).strftime("%B")#
monthYear = "#{monthNumber}-#{yearNumber}"
createdAtCount = 0
creationDateCount = 0 %>
<h1>Stats for <%= monthWord %></h1>
<p><%= monthNumber %>-<%= yearNumber %></p>
<% #votsphonebooks.each do |entry| %>
<% if entry.CreationDate.include? monthYear %>
<p>test</p>
<% end %>
<% end %>
controller
def reports
#votsphonebooks = Votsphonebook.order("id DESC").paginate(:page => params[:page], :per_page => 5000)
end
I can, for example in the loop, run through all the first names, so the loop is working OK, but as soon as I try to test if the 'CreationDate' includes '10-2016' (which also works fine), it gets the error.
CreationDate column has the format: 11-10-2016 - 10:51 AM
Thanks!
I'm trying to get data out of this datamapper object and then putting it into a loop and getting the data out of the object that way, but it doesn't seem to be working, this is the code I have:
#user = User.get(session[:user])
#polls = []
polls = Poll.all(:user_id => #user)
polls.each do |poll|
pollname << poll.name
#polls << pollname
end
and in my erb file:
<% #polls.each do |poll| %>
<p><%= poll %></p>
<% end %>
I thinks what you want is:
#user = User.get(session[:user])
#polls = Poll.where(user_id: #user.id).all.collect { |p| p.name }
In my controller, I'm getting all of a user's associated #highinterest accounts, and I'm adding the sum of the value column:
#dohighinterest = Account.where(user_id: current_user, accounttype: 'Savings', name: ['GE Capital Bank', 'Barclays', 'CIT Bank', 'Bank5 Connect', 'Ally Bank', 'Discover', 'First Choice Bank', 'FNBO Direct', 'Mutual of Omaha', 'Sallie Mae Bank', 'American Express Bank', 'Capital One 360'])
#highinterest = #dohighinterest.sum(&:value)
Later on in the controller, I'm defining variables so that the view knows which class to render.
if #highinterest > (#rechighinterest * 0.8) && (#highinterest < (#rechighinterest * 1.2))
#highrec = "pass"
elsif #highinterest > (#rechighinterest * 0.6) && (#highinterest < (#rechighinterest * 1.4))
#highrec = "okay"
else
#highrec = "fail"
end
Here's the view:
<div class="rollup <%= #highrec %>">
<p>You're gaining interest on</p>
<div class="percentage">
$<%= number_with_delimiter(#highinterest, :delimiter => ',') %>
</div>
</div>
Additionally, I'd like to render a partial in the view if #highrec = "fail" and #highinterest = 0.
What's the best practice for putting that logic into the controller and view? I attempted to define a new variable in the controller #rectext = true if it meets that condition. Then in the view, I wrapped the partial reference to an <%= if #rectext = true %>, but that wasn't returning anything.
I don't think you need a separate variable to hold value of #highrec == "fail" && #highinterest == 0. You can use this same condition in your view. If however there are more variables in play, you could introduce a variable to keep the view cleaner!
<% if #highrec == "fail" && #highinterest == 0 %>
<%= render partial: 'path_to_other_partial' %>
<% else %>
<div class="rollup <%= #highrec %>">
<p>You're gaining interest on</p>
<div class="percentage">
$<%= number_with_delimiter(#highinterest, :delimiter => ',') %>
</div>
</div>
<% end %>
The line you tried <%= if #rectext = true %> would result in syntax error because of <%= tag, which is trying to output the value returned by if #rectext = true. So, a point to note would be, using <%= tag is going to output the value returned by the statements within the tags and <%(without the equals) is going to evaluate only without printing!
Secondly, you are assigning #rectext = true in the if statement, it should be a comparision, i.e. either if #rectext == true or just if #rectext.
You can define a helper method inside folder app/helpers/controllername_helper.rb that recieves the values of #highrec and #highinterest as parameters and then returns true or false depending on your needs.
Then in the view call the method this way:
<% if helper_method_name(#highrec, #highinterest) %>
<%= render partial: 'partial_path' %>
<% end %>
Note that in this code you write :
<%= if #rectext = true %>
you are assigning #rectext the value true and not checking if it is true. Also in this case you should use <% instead of <%=
I am doing this for a school project and it is not working. :(
How do I get out the selected[petowner_id] from the view and make it usable in a ruby controller?
How do I make the #selected_pet = params([petowner_id]) in the controller that comes in from the view to function? Currently it renders an error message when I try to set it. :(
I am getting very tired of it not working.
The controller from Pets controller
class PetsController < ApplicationController
# GET /pets
# GET /pets.json
def monsters
#Finds the current user
if current_user
#user = current_user
#pets_kept = [] #why?
##petowner = Petowner.find(params[:petowner][:id])
#if(params[:commit])
#end
#monster = "Eeeep"
#mypets=[]
#all_my_pets = #user.petowners
#options value = 2
#params { selected_petowner[petowner_id]}
#selectpet = params{[selected][petowner_id]}
#petowner = Petowner.find_by_id(params[:id])
#pet = Pet.find_by_id(params[:pet_id])
#Find the petowners that the user currently has
##mypets = #user.petowners
#This is my way of doing things in a C++ fashion, I don't get all ruby things
#user.petowners.each do |pet|
##selected_pet = pet.find(params[:selected])
# if pet.hp != 0
# #pets_kept << pet #Dont recall seeing the << before in ruby but for C++ statement used for cout statements
#if pet.select
# #selected_pet = pet.select
#end
end
##selected_pet = Petowner.find(params[:petowner][:selected])
#end
#selected_pet = 1 ##user.petowners.find(params[:id])
#mypets = current_user.petowners.select{|pet| pet.hp !=0}
#raise "I am here"
##selected_pet = #mypets.find(params[:id][:selected])
##mypets = #pets_kept
end
The code from the view that doesn't go back to the controller variable and set it. :(
<select id="petowner_id" name="selected[petowner_id]">
<%= #all_my_pets.each do |pet| %>
<option value="<%= pet.id %>"><%= pet.pet_name %></option>
<% end %>
</select>
Previous step from pets/monsters view that doesn't work at all from previous collection. :(
<%= form_for :petowner, :url => petowner_fights_path(#selected_pet, #pet) do |f| %>
<p>Select a pet <%#= f.collection_select(:petowner, :petowner_id, #user.petowners, :petowner_id, :pet_name) %></p>
<%= render 'monsterinfo' %>
<div class="outer"></div>
<%= f.submit "Fight Selected Monster" %>
<% end %>
You probably want params[:petowner][:petowner_id]. Definitely don't construct the select with html in a view.
By the way, it's really helpful to see all of the params passed in to a controller action. I tend to raise params.to_yaml when I need to do that.