In my database I have column :inviter and some users have same content in that column
I want find all them,with same content
In my user controller:
def foll
#user = current_user
#ref = User.find_by_invite(#user.id.to_s)
if !#ref || !#ref.pay_s || !#ref.pay_1 || !#ref.pay_2 || !#ref.pay_3
#referals = false
else
#referals = User.find_by_invite(#user.id.to_s)
end
end
In my views
<% if #referals != false %>
<% #referals.each do |user| %>
<h4>
<%= link_to user.name, user %> status : Good
</h4>
<% end %>
<% else %>
<h3>You dont have any referrals</h3>
<% end %>
When I try I have this error
undefined method `each' for #<User:0x007f13e41b0068>
this will raise error since
#referals = User.find_by_invite(#user.id.to_s)
will return single record
you can try #where to query all referrals
#referals = User.where(invite: #user.id.to_s)
you can also refer here for other queries
http://guides.rubyonrails.org/active_record_querying.html
hope this helps
Hope this help:
controller:
def foll
#user = current_user
#ref = User.find_by_invite(#user.id.to_s)
if !#ref || !#ref.pay_s || !#ref.pay_1 || !#ref.pay_2 || !#ref.pay_3
#referals = []
else
#referals = User.where(invite: #user.id.to_s)
end
end
view:
<% if #referals.any? %>
<% #referals.each do |user| %>
<h4>
<%= link_to user.name, user %> status : Good
</h4>
<% end %>
<% else %>
<h3>You dont have any referrals</h3>
<% end %>
Related
I'm implementing a full text search with sunspot, in which I store the text fields in order to get highlighted results. When it's just a fulltext it works fine without conjunctions, but when you have to put conjunctions it doesn't show up, it does the search fine, but the highlighting doesn't show up.
search model code:
def search
#search = Sunspot.new_search(DigitalEntity)
build_fields_searchs_search
#search.execute
end
def build_fields_searchs_search
object = self
#search.build do
any do
object.fields_searchs.select { |x| x.conjunction == 'or' }.each do |fields_search|
adjust_solr_params do |params|
if params[:q].present? && fields_search.conjunction == 'not'
params[:q] = params[:q].sub('OR _query', 'OR NOT _query')
end
end
if (fields_search.filter == 'begins') && fields_search.discovery_field
with(fields_search.discovery_field.identifier.to_sym).starting_with(fields_search.value)
else
fulltext fields_search.value do
highlight title: true
highlight description: true
highlight coverage: true
highlight fulltext: true
fields fields_search.discovery_field.identifier.to_sym if fields_search.discovery_field
minimum_match(1) if fields_search.filter == 'contains'
boost(2.0) { with(:users_email_bookmark, user.email) } if user
end
end
if fields_search.start_date && !fields_search.end_date
with(:date).greater_than_or_equal_to(fields_search.start_date)
elsif !fields_search.start_date && fields_search.end_date
with(:date).less_than_or_equal_to(fields_search.end_date)
elsif fields_search.start_date && fields_search.end_date
with(:date).between(fields_search.start_date..fields_search.end_date)
end
end
all do
object.fields_searchs.reject { |x| x.conjunction == 'or' }.each do |fields_search|
if fields_search.filter == 'exactly' && !fields_search.value.match('"')
fields_search.value = '"' + fields_search.value + '"'
end
adjust_solr_params do |params|
if params[:q].present? && fields_search.conjunction == 'not'
params[:q] = params[:q].sub('AND _query', 'AND NOT _query')
end
end
if (fields_search.filter == 'begins') && fields_search.discovery_field
with(fields_search.discovery_field.identifier.to_sym).starting_with(fields_search.value)
else
fulltext object.fields_searchs.value do#pluck(:value).join(" AND ") do
highlight :title
highlight :description
highlight :coverage
highlight :fulltext
highlight :contributor
fields fields_search.discovery_field.identifier.to_sym if fields_search.discovery_field
minimum_match(1) if fields_search.filter == 'contains'
boost(2.0) { with(:users_email_bookmark, user.email) } if user
end
end
if fields_search.start_date && !fields_search.end_date
with(:date).greater_than_or_equal_to(fields_search.start_date)
elsif !fields_search.start_date && fields_search.end_date
with(:date).less_than_or_equal_to(fields_search.end_date)
elsif fields_search.start_date && fields_search.end_date
with(:date).between(fields_search.start_date..fields_search.end_date)
end
end
end
end
end
end
searches helper:
def show(identifier, hit, opts = { sep: ', ' })
return '' unless hit
if hit.highlight(identifier)
highlights_for(identifier, hit)
else
raw(content(hit.stored(identifier), separator: opts[:sep], max_length: opts[:max_length])) unless(identifier == :fulltext)
end
end
def highlights_for(identifier, hit)
output = ''
hit.highlights(identifier).each do |h|
output += h.format { |word| "<span style='background-color: #eee5d5;color: #9E2D37;'>#{word}</span>" }
end
raw(output)
end
view code
<div class="content">
<h4 class="title">
<%= link_to link_url, remote: remote_link, style: "color: black !important", id: "item-#{item.primary_key}" do %>
<% if item.stored(:title) %>
<% title = item.stored(:title).first %>
<%= show(:title, item) %>
<% end %>
<% end %>
</h4>
<!-- fulltext -->
<% if show(:fulltext, item) && params["dem_discovery_search"]["is_fulltext_search"] == "1" %>
<div style="font-style: italic !important;font-family: 'Open Sans', sans-serif;font-size: 13px;"><%= show(:fulltext, item)%></div>
<% end %>
<!-- by creator -->
<% if item.stored(:contributor) != nil %>
<p><%= t(:by) %> <%= item.stored(:contributor).first %></p>
<% end %>
<% if item.stored(:description) != nil %>
<p><%= item.stored(:description).first %></p>
<% end %>
<!-- date -->
<!-- first coverage -->
<% if item.stored(:coverage) != nil %>
<p><%= show(:coverage, item)%> </p>
<% end %>
<span data-emerald-hook='discovery_item_details_extra'></span>
</div>
</div>
Sunspot Search printed
If I am searching by field title, query "prueba" THIS WORKS!
<Sunspot::Search:{:fq=>["type:Emerald\\:\\:Dem\\:\\:DigitalEntity"], :q=>"prueba", :fl=>"* score", :qf=>"title_texts contributor_texts creator_texts publisher_texts date_old_texts coverage_texts type_texts description_texts relation_texts subject_texts source_texts format_texts identifier_texts language_texts loan_texts rights_holder_texts rights_texts audience_texts provenance_texts instructional_method_texts accrual_method_texts accrual_periodicity_texts accrual_policy_texts parent_title_texts bibliotecaDipositaria_texts document_type_texts abstract_texts catalogue_url_texts text_date_texts temporal_texts titolPrincipal_texts isReplacedBy_texts replaces_texts fulltext_texts", :defType=>"edismax", :mm=>1, :bq=>["users_email_bookmark_sms:admin#greendata\\.com^2.0"], :hl=>"on", :"hl.simple.pre"=>"###hl###", :"hl.simple.post"=>"###endhl###", :"hl.fl"=>["title_texts", "description_texts", "fulltext_texts", "contributor_texts"], :start=>0, :rows=>30}>
If I am searching by field title, query "prueba" AND field description "descripcion" NOT WORKING!
<Sunspot::Search:{:fq=>["type:Emerald\\:\\:Dem\\:\\:DigitalEntity"], :q=>"(_query_:\"{!edismax qf='title_texts contributor_texts creator_texts publisher_texts date_old_texts coverage_texts type_texts description_texts relation_texts subject_texts source_texts format_texts identifier_texts language_texts loan_texts rights_holder_texts rights_texts audience_texts provenance_texts instructional_method_texts accrual_method_texts accrual_periodicity_texts accrual_policy_texts parent_title_texts bibliotecaDipositaria_texts document_type_texts abstract_texts catalogue_url_texts text_date_texts temporal_texts titolPrincipal_texts isReplacedBy_texts replaces_texts fulltext_texts' mm='1' bq='users_email_bookmark_sms:admin#greendata\\.com^2.0' hl='on' hl.simple.pre='###hl###' hl.simple.post='###endhl###' hl.fl='title_texts description_texts fulltext_texts contributor_texts'}prueba\" AND _query_:\"{!edismax qf='title_texts contributor_texts creator_texts publisher_texts date_old_texts coverage_texts type_texts description_texts relation_texts subject_texts source_texts format_texts identifier_texts language_texts loan_texts rights_holder_texts rights_texts audience_texts provenance_texts instructional_method_texts accrual_method_texts accrual_periodicity_texts accrual_policy_texts parent_title_texts bibliotecaDipositaria_texts document_type_texts abstract_texts catalogue_url_texts text_date_texts temporal_texts titolPrincipal_texts isReplacedBy_texts replaces_texts fulltext_texts' mm='1' bq='users_email_bookmark_sms:admin#greendata\\.com^2.0' hl='on' hl.simple.pre='###hl###' hl.simple.post='###endhl###' hl.fl='title_texts description_texts fulltext_texts contributor_texts'}descripcion\")", :fl=>"* score", :start=>0, :rows=>30}>
what am I doing wrong?
any suggestion would be welcome
if you need more parts of code do not hesitate to ask me
Thanks in advance!
I am using Ruby on Rails 5.2.3 and Mongoid 7.0
I need to be able to sort multiple models (Item and Text) in one cotroller.
Now only Item or Text is sorted, it is necessary that Position was set in relation to each other.
class UsersController < ApplicationController
def sort
params[:item].each_with_index do |id, index|
Item.where(id: id).update_all(position: index + 1)
end
head :ok
end
def admin
#user_items = #user.user_feed
end
end
admin.html.erb
<div id="items" data-url="<%= sort_users_path %>">
<%= render partial: 'users/user_item', collection: #user_items %>
</div>
_user_item.html.erb
<% if user_item[:title].present? %>
<div id="item_<%= user_item[:id] %>">
<%= user_item[:position] %>
</div>
<% end %>
<% if user_item[:text].present? %>
<div id="item_<%= user_item[:id] %>">
<%= raw user_item[:position] %>
</div>
<% end %>
User.rb
def user_activity
activity_items = []
items.each do |item|
activity_item = {}
activity_item[:id] = item.id
activity_item[:url] = item
activity_item[:title] = item.title
activity_item[:position] = item.position
activity_item[:item_link] = item.url
activity_items << activity_item
end
texts.each do |text|
activity_item = {}
activity_item[:id] = text.id
activity_item[:url] = text
activity_item[:text] = text.text
activity_item[:position] = text.position
activity_items << activity_item
end
activity_items.sort_by! { |activity_item| activity_item[:position] }
activity_items
end
def user_feed
activity_items = user_activity
activity_items.sort_by! { |activity_item| activity_item[:position] }
activity_items
end
Just needed to add Text.where(id: id).update_all(position: index + 1)
def sort
params[:item].each_with_index do |id, index|
Item.where(id: id).update_all(position: index + 1)
Text.where(id: id).update_all(position: index + 1)
end
head :ok
end
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.
I got four different models.
Here's an example,
#single = Single.all
#coe = Coe.all
#blend = Blend.all
#production = #single+#coe+#blend
then how to check which model #production is?
I tried
<% #production.each do |p| %>
<%=p.class.name%>
<% end %>
but it returns "Array"
It seems to be simple, but I can't find out
(I edited question)
The problem is here
#single = Single.all
#coe = Coe.all
#blend = Blend.all
#production = #single+#coe+#blend
change these lines with
#single = Single.all.to_a
#coe = Coe.all.to_a
#blend = Blend.all.to_a
#production = #single+#coe+#blend
and then if you will check
#production.first.class.name #Single
#production.last.class.name #Blend
so in your view you can do this
<% #production.each do |p| %>
<% p.each do |product| %>
<%= product.class.name %>
<% end %>
<% end %>
if while iterating on #production it returns array so you need to try this.
<% #production.each do |p| %>
<% p.each do |product| %>
<%= product.class.name %>
<% end %>
<% end %>
#production is a collections of combinations of single, coe, and blend thats why #production.class.name doesnt work, you need to iterate each object like this:
<% #production.each do |object| %>
<%= object.class.name %>
<% end %>
I am attempting to perform a series of requests that will organize the results in a given date span in a way where each location will live on the top level, and contain an another array with each set of results. Here is what I have so far:
locations = Location.all
#requests = []
locations.each do |location|
request = PurchaseRequest.where('created_at >= ? AND created_at <= ? AND location_id = ?', params[:start_date], params[:end_date], location.id).order(:location_id)
#requests.push(location => request)
end
My ideal (non-working) implementation in the view would look something like:
<ul>
<% #requests.each do |location| %>
<li>location[0].name</li>
<ul>
<% location[1].each do |request| %>
<li>request.name</li>
<% end %>
</ul>
<% end %>
</ul>
Try something like this:
#requests = {}
Location.all.each do |location|
#requests[location.name] = PurchaseRequest.where('created_at >= ? AND created_at <= ? AND location_id = ?', params[:start_date], params[:end_date], location.id).order(:location_id)
end
and:
<ul>
<% #requests.each do |location_name, request_list| %>
<li><%= location_name %></li>
<ul>
<% request_list.each do |request| %>
<li><%= request.name %></li>
<% end %>
</ul>
<% end %>
</ul>
#requests becomes a hash with the key being the location name and the value being the purchase requests.