Operand should contain 1 column(s) ruby on rails - mysql

I have 3 model Shop Section and Price, Section have shop_id and Price have section_id
How can i show prices in Shop view?
controller/shop_controller.rb
...
def show
#metod_one = Magazine.find(params[:id])
#method_two = Section.find(:all, :conditions => ['shop_id = ?', #method_one])
#method_three = Price.find(:id, :conditions => ['section_id = ?', #method_two])
end
...
This method don't work
Mysql::Error: Operand should contain 1 column(s): SELECT * FROM prices WHERE (prices.id = '--- :id\n' AND (section_id = 5480,5482,5483,5485))

Please try the in operator:
#method_three = Price.find(:all, :conditions => ['section_id in (?)', #method_two])

Related

Subquery By Zend Database Format

I created a query in MYSQL as follows :
select subsql.item_id, subsql.uid, subsql.post_date, subsql.uid_prev,
max(workflow_trans.date) AS pre_date
from (
select item_id, max(date) AS post_date, uid, uid_prev
from workflow_trans
where uid = 'name' and date <= 'date1' and date >= 'date2'
group by item_id, uid, uid_prev
) AS subsql
left join workflow_trans on subsql.item_id = workflow_trans.item_id and
subsql.uid_prev = workflow_trans.uid and subsql.post_date > workflow_trans.date
where workflow_trans.date is not null
group by subsql.item_id, subsql.uid, subsql.post_date, subsql.uid_prev
order by subsql.post_date
The In translated it to Zend DB format as follows :
$this->db->select()->from(array("subsql" => $this->db->select()
->from(array($this->_name), array('item_id', 'max(date) AS post_date',
'uid', 'uid_prev'))
->where("uid = ?", $username)->where("date >= ?", $tgl1)
->where("date <= ?", $tgl2)
->group(array('item_id', 'uid', 'uid_prev'))),
array('subsql.item_id','subsql.uid',
'subsql.post_date','subsql.uid_prev','max(workflow_trans.date)
as pre_date'))
->joinLeft($this->_name, 'subsql.item_id = workflow_trans.item_id
and subsql.uid_prev = workflow_trans.uid and subsql.post_date >
workflow_trans.date')
->where("workflow_trans.date != ?", null)
->group(array('subsql.item_id', 'subsql.uid', 'subsql.post_date',
'subsql.uid_prev'))
->order(array('subsql.post_date'))
Yet the Zend model could not working. i've been reexamined it, and made 3 changes, but still there is something wrong with the formatting. Fresh pair of sharp eyes are appreciated.
ANSWER UPDATE
Hello guys, I already found it, below the running code :
$this->db->select()->from(array("subsql" => $this->db->select()
->from(array($this->_name), array('item_id', 'max(date) AS post_date',
'uid', 'uid_prev'))
->where("uid = ?", $username)->where("date >= ?", $tgl1)
->where("date <= ?", $tgl2)
->group(array('item_id', 'uid', 'uid_prev'))),
array('subsql.item_id','subsql.uid','subsql.post_date','subsql.uid_prev'))
->joinLeft(array($this->_name), 'subsql.item_id = workflow_trans.item_id and
subsql.uid_prev = workflow_trans.uid and
subsql.post_date > workflow_trans.date',
array('max(workflow_trans.date) as pre_date'))
->where("workflow_trans.date is not null")
->group(array('subsql.item_id', 'subsql.uid', 'subsql.post_date',
'subsql.uid_prev'))
->order(array('subsql.post_date'));
You should define the column from joining table in its own join function, and of course I got it wrong on how to handle the null.
If we talks about zf3, this query generates same sql as with yours.
$from = $this->getSql()->select('workflow_trans')
->columns(['item_id, max(date) AS post_date, uid, uid_prev', new Literal('max(workflow_trans.date) AS pre_date')])
->where(['uid = ?' => 'name'])
->where(['date <= ?' => 'date1'])
->where(['date >= ?' => 'date2'])
->group(['item_id', 'uid', 'uid_prev']);
$query = $this->getSql()->select()
->columns(['item_id, uid, post_date, uid_prev'])
->from(['subsql' => $from])
->join('workflow_trans', 'subsql.item_id = workflow_trans.item_id and subsql.uid_prev = workflow_trans.uid and subsql.post_date > workflow_trans.date', [])
->where(new IsNotNull('workflow_trans.date'))
->group(['subsql.item_id', 'subsql.uid', 'subsql.post_date', 'subsql.uid_prev'])
->order('subsql.post_date');

Remove deprecated `:distinct` option from `Relation#count` for Rails 4.1

Code:
checkin_scope.count(:select => "user_id", :distinct => true)
SQL query
SELECT COUNT(DISTINCT `checkins`.`user_id`) AS count_user_id,
location_id AS location_id
FROM `checkins` INNER JOIN `locations` ON `locations`.`id` = `checkins`.`location_id`
WHERE `checkins`.`business_id` = 452 AND `checkins`.`status` = 'loyalty'
AND `locations`.`status` = 'approved' AND
`checkins`.`location_id` IN (302825, 302838, 302839, 302901)
AND (date(checkins.created_at) between '2014-10-11' and '2014-11-11')
GROUP BY location_id
I need to remove :distinct => true as it has been removed in Rails 4.1.
Ok, I could solve the problem
checkin_scope.count("DISTINCT(checkins.user_id)")
where checkin_scope is a method,
def checkin_scope
cscope = #business.checkins.loyalty_punchh.joins(:location).where(:locations => {:status => "approved"}).group(:location_id)
cscope = cscope.for_location(#location) if #location
if #from && #to
cscope = cscope.where("date(checkins.created_at) between ? and ?",#from.to_date,#to.to_date)
end
cscope
end

unknown column mysql where clause - but I can access and set it within my app. what is causing this?

models:
class Change < ActiveRecord::Base
attr_accessor :selected_end_index, :selected_start_index, :revision_number
error:
ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'revision_number' in 'where clause': SELECT * FROM `changes` WHERE (kind = 2 && status = -1 && content_id = 2 && revision_number = 0) ORDER BY id DESC
method:
def new_change_requests_for_latest_version
changes = Change.find(:all,
:conditions => ["kind = ? && status = ? && content_id = ? && revision_number = ?",
Change::CHANGE, Change::NEW, self[:id], self.current_version],
:order => "id DESC")
return changes
end
It means there is no column named "revision_number". The reason you can access it in your app is because attr_accessor sets up the field in the in-memory object. But any value assigned to it will not be persisted in the database, nor can you query on it.

Count number of rows with distinct column

I'm trying to count the number of rows with a distinct column with Active Record.
The following SQL works and gives me the correct result:
SELECT COUNT(DISTINCT(user_id)) FROM attempts WHERE score = 100 AND problem_id = 1
But this code throws an ActiveRecord::StatementInvalid error:
attempts.where(:score => 100).count(:distinct => :user_id)
Try:
attempts.count('user_id', :conditions => "score = 100", :distinct => true)
more infos: http://ar.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html

Alternative as NOT IN gives a blank array

I have a query in my rails application,
user_info = Information.where("user_id = ? and department_id NOT IN (?)",user.id, Department.unapproved_departments ).all(:include => [:name, :project]).
Here unapproved_departments contains an array of ids in Department table.
The problem arises when unapproved_departments is a blank array.In those cases "NOT IN"
checks for ids present in the array and entire user_info is returned as a blank array.
So i would like to have all the data with ids other than those in unapproved_departments array or you can say an alternative for NOT IN
Thanx
Theres nothing wrong with NOT IN -- just that you don't want it to fire when there's nothing there.
I suggest:
user_info = Information.where("user_id = ?", user)
unapproved_departments = Department.unapproved_departments
if unapproved_departments.present? # true if not blank or nil
user_info = user_info.where("department_id NOT IN (?)", unaproved_departments)
end
user_info.all(:include => [:name, :project])
As you can see, you can chain the conditions together.
Can't you just have a special case for when unapproved_departments is empty?
if Department.unapproved_departments.empty?
user_info = Information.where("user_id = ?",user.id).all(:include => [:name, :project])
else
user_info = Information.where("user_id = ? and department_id NOT IN (?)",user.id, Department.unapproved_departments ).all(:include => [:name, :project])
end
it will be better if you define better unapproved_departments to retun [nil] instead of []
Oterwhise you can add [0] to your code :
user_info = Information.where("user_id = ? and department_id NOT IN (?)",user.id, (Department.unapproved_departments << 0) ).all(:include => [:name, :project]).
If we concentrate just on the "NOT IN" part:
user_info = Information.where("department_id NOT IN (?)", []).to_sql
# => SELECT `informations`.* from `informations` where department_id not in (NULL)
Which is weird because of null-tests: http://dev.mysql.com/doc/refman/5.0/en/working-with-null.html
What we can do is reverse the test and get the required result:
user_info = Information.where("NOT (department_id IN (?))", []).to_sql
# => SELECT `informations`.* from `informations` where NOT (department_id in (NULL))
It works because in MySQL everything is != NULL (and also < NULL and > NULL at same time!).