Hi I followed the link to set up closure_tag gem.
When i tried to use closure_tree syntax in the following way (newStructure.find_or_create_by_path(parent) instead of newStructure.move_to_child_of(parent)) ... got the following error :
"Can't mass-assign protected attributes: ancestor, descendant, generations"
is this the correct way of using newStructure.find_or_create_by_path(parent) ?
def self.import(path)
newStructure = FileOrFolder.find(:first, :conditions=>["fullpath = ?", path])
if newStructure
return newStructure
end
newStructure = FileOrFolder.new
newStructure.fullpath = path
pathbits = path.split('/')
newStructure.name = pathbits.last
newStructure.save
parentpath = path.sub(/#{Regexp.escape(pathbits.last)}$/, '')
if parentpath.length > 1
parentpath.sub!(/\/$/,'')
parent = FileOrFolder.find(:first, :conditions=>["fullpath = ?", parentpath])
unless parent
parent = FileOrFolder.import(parentpath)
end
#newStructure.move_to_child_of(parent);
**newStructure.find_or_create_by_path(parent);**
end
newStructure.save
return newStructure
end
database table looks like :
mysql> select * from testdb7.file_or_folders limit 10;
+------+-----------+------+------+----------+------------------------+---------------------+---------------------+
| id | parent_id | lft | rgt | fullpath | name | created_at | updated_at |
+------+-----------+------+------+----------+------------------------+---------------------+---------------------+
| 6901 | NULL | NULL | NULL | NULL | | 2013-06-25 18:49:04 | 2013-06-25 18:49:04 |
| 6902 | 6901 | NULL | NULL | NULL | devel | 2013-06-25 18:49:04 | 2013-06-25 18:49:04 |
| 6903 | 6902 | NULL | NULL | NULL | Bcontrol | 2013-06-25 18:49:04 | 2013-06-25 18:49:04 |
| 6904 | 6903 | NULL | NULL | NULL | perfect | 2013-06-25 18:49:04 | 2013-06-25 18:49:04 |
| 6905 | 6904 | NULL | NULL | NULL | matlab | 2013-06-25 18:49:04 | 2013-06-25 18:49:04 |
| 6906 | 6905 | NULL | NULL | NULL | test | 2013-06-25 18:49:04 | 2013-06-25 18:49:04 |
| 6907 | 6906 | NULL | NULL | NULL | smoke | 2013-06-25 18:49:04 | 2013-06-25 18:49:04 |
| 6908 | 6907 | NULL | NULL | NULL | Control_System_Toolbox | 2013-06-25 18:49:04 | 2013-06-25 18:49:04 |
| 6909 | 6908 | NULL | NULL | NULL | tsmoke_are.m | 2013-06-25 18:49:04 | 2013-06-25 18:49:04 |
| 6910 | 6908 | NULL | NULL | NULL | tsmoke_bode.m | 2013-06-25 18:49:04 | 2013-06-25 18:49:04 |
+------+-----------+------+------+----------+------------------------+---------------------+---------------------+
FileOrFolder Load (14560.8ms) SELECT `file_or_folders`.* FROM `file_or_folders` INNER JOIN `file_or_folder_hierarchies` ON `file_or_folders`.`id` = `file_or_folder_hierarchies`.`descendant_id` INNER JOIN (
SELECT ancestor_id
FROM `file_or_folder_hierarchies`
GROUP BY 1
HAVING MAX(`file_or_folder_hierarchies`.generations) = 0
) AS leaves ON (`file_or_folders`.id = leaves.ancestor_id) WHERE `file_or_folder_hierarchies`.`ancestor_id` = 147 ORDER BY `file_or_folder_hierarchies`.generations asc
EXPLAIN (13343.7ms) EXPLAIN SELECT `file_or_folders`.* FROM `file_or_folders` INNER JOIN `file_or_folder_hierarchies` ON `file_or_folders`.`id` = `file_or_folder_hierarchies`.`descendant_id` INNER JOIN (
SELECT ancestor_id
FROM `file_or_folder_hierarchies`
GROUP BY 1
HAVING MAX(`file_or_folder_hierarchies`.generations) = 0
) AS leaves ON (`file_or_folders`.id = leaves.ancestor_id) WHERE `file_or_folder_hierarchies`.`ancestor_id` = 147 ORDER BY `file_or_folder_hierarchies`.generations asc
EXPLAIN for: SELECT `file_or_folders`.* FROM `file_or_folders` INNER JOIN `file_or_folder_hierarchies` ON `file_or_folders`.`id` = `file_or_folder_hierarchies`.`descendant_id` INNER JOIN (
SELECT ancestor_id
FROM `file_or_folder_hierarchies`
GROUP BY 1
HAVING MAX(`file_or_folder_hierarchies`.generations) = 0
) AS leaves ON (`file_or_folders`.id = leaves.ancestor_id) WHERE `file_or_folder_hierarchies`.`ancestor_id` = 147 ORDER BY `file_or_folder_hierarchies`.generations asc
+----+-------------+----------------------------+--------+------------------------------------------------------------------------------------+----------------------------------+---------+--------------------+---------+---------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------------------------+--------+------------------------------------------------------------------------------------+----------------------------------+---------+--------------------+---------+---------------------------------+
| 1 | PRIMARY | file_or_folder_hierarchies | ref | index_file_or_folders_on_ans_des,index_file_or_folder_hierarchies_on_descendant_id | index_file_or_folders_on_ans_des | 4 | const | 15 | Using temporary; Using filesort |
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 104704 | Using where; Using join buffer |
| 1 | PRIMARY | file_or_folders | eq_ref | PRIMARY | PRIMARY | 4 | leaves.ancestor_id | 1 | Using where |
| 2 | DERIVED | file_or_folder_hierarchies | index | NULL | index_file_or_folders_on_ans_des | 8 | NULL | 1340096 | |
+----+-------------+----------------------------+--------+------------------------------------------------------------------------------------+----------------------------------+---------+--------------------+---------+---------------------------------+
I'm the author of closure_tree. 4.2.3 is on it's way with the fix for attr_accessible. I'm just waiting for Travis to finish testing it.
It looks like your whole import method could be replaced with this line:
# Assumes that path is a string that looks like this: "/usr/local/bin/ruby"
def import(path)
FileOrFolder.find_or_create_by_path(path.split("/"))
end
This assumes you have this FileOrFolder setup:
class FileOrFolder < ActiveRecord::Base
acts_as_tree
before_create :set_fullpath
def set_fullpath
if root?
self.fullpath = "/#{name}"
else
self.fullpath = "/#{parent.ancestry_path.join("/")}/#{name}"
end
end
end
Please take a look at the spec directory. You'll find tons of other examples.
Related
I have three tables topics, category(HowtoCategory::class), sections(Howto::class).
Multiple categories belong to one topic and multiple sections belong to one category.
Topic Has Many Category
Category Has Many Sections
Category Belongs to Topic
Sections Belongs To Category
Topic Has Many Sections Through Category
I want to search through the sections(Howto::class) but display the related topics. How can I access topics in the controller from my query search of sections? I dont want to access it in the view but in the controller.
Controller
public function index(Request $request)
{
if (request()->filled('search')) {
request()->fullUrlWithQuery(['search ' => null]);
$sections = Howto::search($request->search)->get();
$request = $request->input('search');
} else {
$sections = null;
}
return view('howto-pages.howto-main', [
'sections' => $sections,
]);
}
Models
class Topic extends Model
{
public function categories()
{
return $this->hasMany(HowtoCategory::class);
}
public function sections()
{
return $this->hasManyThrough(Howto::class, HowtoCategory::class);
}
}
class HowtoCategory extends Model
{
public function sections()
{
return $this->hasMany(Howto::class);
}
public function topic()
{
return $this->belongsTo(Topic::class);
}
}
class Howto extends Model
{
public function category()
{
return $this->belongsTo(HowtoCategory::class);
}
}
Tables
mysql> desc howto;
+-------------------+-----------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+-----------------+------+-----+---------+----------------+
| id | bigint unsigned | NO | PRI | NULL | auto_increment |
| title | varchar(255) | NO | | NULL | |
| body | mediumtext | YES | | NULL | |
| description | mediumtext | YES | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
| section_id | int | YES | | NULL | |
| howto_category_id | bigint unsigned | YES | MUL | NULL | |
+-------------------+-----------------+------+-----+---------+----------------+
mysql> desc howto_category;
+----------------------+-----------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------------+-----------------+------+-----+---------+----------------+
| id | bigint unsigned | NO | PRI | NULL | auto_increment |
| howto_category_title | varchar(255) | NO | | NULL | |
| icon | varchar(255) | YES | | NULL | |
| description | mediumtext | YES | | NULL | |
| intro | text | YES | | NULL | |
| category_id | int | YES | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
| topic_id | bigint unsigned | YES | MUL | NULL | |
+----------------------+-----------------+------+-----+---------+----------------+
mysql> desc topics;
+-------------+-----------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-----------------+------+-----+---------+----------------+
| id | bigint unsigned | NO | PRI | NULL | auto_increment |
| topic_title | varchar(255) | NO | | NULL | |
| description | mediumtext | YES | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
+-------------+-----------------+------+-----+---------+----------------+
First and foremost i'd define the foreignIDS in the relations just to make sure that are working as expected.
class Topic extends Model
{
public function categories()
{
return $this->hasMany(HowtoCategory::class);
}
public function sections()
{
return $this->hasManyThrough(
Howto::class, HowtoCategory::class,
"topic_id", "howto_category_id"
);
}
}
then you can get the Topics by searching the sections like so
use Illuminate\Database\Eloquent\Builder;
$topics = Topic::whereHas("sections", function(Builder $query) {
$query->where("howto.description", "something to search")
})->get();
I'm using cockroachdb, which is essentially a superset of postgres and I can't understand why the statement:
select * from _a66df261120b6c23.tabDefaultValue;
results sin the error:
ERROR: relation "_a66df261120b6c23.tabdefaultvalue" does not exist
show databases gives me:
database_name | owner | primary_region | regions | survival_goal
--------------------+-------+----------------+---------+----------------
_a66df261120b6c23 | root | NULL | {} | NULL
defaultdb | root | NULL | {} | NULL
postgres | root | NULL | {} | NULL
root | root | NULL | {} | NULL
sammy | root | NULL | {} | NULL
system | node | NULL | {} | NULL
test123 | root | NULL | {} | NULL
test3 | root | NULL | {} | NULL
test4 | root | NULL | {} | NULL
test5 | root | NULL | {} | NULL
test9 | root | NULL | {} | NULL
and show tables from _a66df261120b6c23 gives me:
schema_name | table_name | type | owner | estimated_row_count | locality
--------------+-------------------+-------+-------+---------------------+-----------
public | __Auth | table | root | 0 | NULL
public | tabDefaultValue | table | root | 0 | NULL
The database and the table both exist, so why does select * from _a66df261120b6c23.tabDefaultValue; fail? Strange thing is when I run \dt all I get is:
schema_name | table_name | type | owner | estimated_row_count | locality
--------------+------------+-------+-------+---------------------+-----------
public | sammy | table | root | 0 | NULL
How do I actually get the select statement to work? Thank you
SQL statements are case sensitive and incoming identifiers are lowercased unless specifically forced with double quotes.
This means that to refer to your tabDefaultValue, you need to use the following statement:
select * from _a66df261120b6c23."tabDefaultValue";
Note that the quotes are around the table name only, if you quote dbname.tablename together, this will be considered a single identifier with a dot in the middle.
I have a table on my DB with these columnns:
+-----------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+---------------------+------+-----+---------+----------------+
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
| value | varchar(255) | NO | | NULL | |
+-----------------+---------------------+------+-----+---------+----------------+
I would access to value values by name.
For example I have these datas:
+----+------------+------------+
| id | name | value |
+----+------------+------------+
| 1 | start_date | 2020-01-01 |
| 2 | end_date | 2021-01-01 |
+----+------------+------------+
I would to get '2020-01-01' by 'start_date'.
I tried this code, but I'm not satisfyed because with this code I get all values of the row, not only the value expected.
Configuration::get()->keyBy('start_date');
I'm not sure I was clear.
Let me know.
Thanks a lot!!
Assuming you want to get an array of key/value pairs, and each key in the name column is unique, you can simply use pluck() (https://laravel.com/docs/8.x/collections#method-pluck):
$configuration = Configuration::pluck('value', 'name');
dd($configuration);
// ['start_date' => '2020-01-01', 'end_date' => '2021-01-01']
Then, you'd use simply array access to use these configuration settings where applicable:
$startDate = $configuration['start_date']; // '2020-01-01'
$endDate = $configuration['end_date']; // '2021-01-01'
...
I have three tables:
- Venue
- Space (belongs to Venue)
- Included Space (belongs to Space)
I receive the id of a Venue in the route and return all the related spaces that I know have Included Spaces(a field called num_included_spaces__c on the Space record that maintains a count of its children). Now that I have all the related parent Spaces for that Venue, I need to find all of the Included Spaces for them.
An Included Space is still a Space, it just happens to have a parent that resides in the same table. I'm trying to turn this:
Venue = Rockdog
- Space = Upstairs
- Space = Media Room
- Space = Courtyard
- Space = Downstairs
- Space = Front Patio
- Space = Indoor Bar
Into this:
Venue = Rockdog
- Space = Upstairs
-- Included Space = Media Room
-- Included Space = Courtyard
- Space = Downstairs
-- Included Space = Front Patio
-- Included Space = Indoor Bar
The Included Spaces table has belongs_to__c and space__c as fields, where belongs_to__c is the id of the parent space and space__c is the id of the child. So i'm looking to find all the Included Spaces where belongs_to_c matches the id of any #spaces returned below
#sub_spaces = Space.where("venue__c = ? AND num_included_spaces__c = ?", params[:venue],0)
#spaces = Space.where("venue__c = ? AND num_included_spaces__c > ?", params[:venue],0)
How would I write this Active Record Query for #included_spaces?
my database schema.
mysql> describe venues;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
4 rows in set (0,00 sec)
mysql> describe spaces;;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
| venue_id | int(11) | YES | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
5 rows in set (0,00 sec)
ERROR:
No query specified
mysql> describe included_spaces;;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
| space_id | int(11) | YES | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
5 rows in set (0,00 sec)
ERROR:
No query specified
Below function will somehow give you the result you need (in console ofcourse ) however it's not a good solution - it queries database more than needed. However it is the easy -))
def foo id
v = Venue.find(id)
puts v.name
v.spaces.each do |space|
puts space.name
space.included_spaces.each do |spis|
puts spis.name
end
end
end
You can also try a more complex query sth like,
mysql> SELECT spaces.name, included_spaces.name FROM `spaces` INNER JOIN `venues` ON `venues`.`id` = `spaces`.`venue_id` INNER JOIN `included_spaces` ON `included_spaces`.`space_id` = `spaces`.`id` WHERE `spaces`.`venue_id` = 1
-> ;
+------------+-----------+
| name | name |
+------------+-----------+
| Upstairs, | Front |
| Upstairs, | Patio, |
| Upstairs, | Indoor |
| Upstairs, | Bar |
| Downstairs | Media |
| Downstairs | Room, |
| Downstairs | Courtyard |
+------------+-----------+
7 rows in set (0,00 sec)
which should be translated to active record as
Space.joins(:venue)
.joins(:included_spaces)
.where(venue_id: 1)
.select('spaces.name, included_spaces.name')
I have got a table with name table_listnames whose structure is given below
mysql> desc table_listnames;
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
+-------+--------------+------+-----+---------+----------------+
2 rows in set (0.04 sec)
It has got sample data as shown
mysql> select * from table_listnames;
+----+------------+
| id | name |
+----+------------+
| 6 | WWW |
| 7 | WWWwww |
| 8 | WWWwwws |
| 9 | WWWwwwsSSS |
| 10 | asdsda |
+----+------------+
5 rows in set (0.00 sec)
I have a requirement where if name not found under the table , i need to insert or else do nothing
I am achieving it this way
String sql = "INSERT INTO table_listnames (name) SELECT name FROM (SELECT ?) AS tmp WHERE NOT EXISTS (SELECT name FROM table_listnames WHERE name = ?) LIMIT 1";
pst = dbConnection.prepareStatement(sql);
pst.setString(1, salesName);
pst.setString(2, salesName);
pst.executeUpdate();
Is it possible to know the id of the record of the given name in this case