Second if statement in jade layout not working - node.js

The first if statement is firing corretly and marking the checkbox as checked when the value is true, but the second isn't.
- var profileVal = false
- var logbookVal = false
div.form-group.col-md-6
-if(user.profilePublic){
- profileVal = true
-}
label Public profile
p Would you like your profile to be public?
input(type='checkbox',name='userPublicProfile',class='floatLeftCheckbox',checked=profileVal)
div.form-group.col-md-6.clearfix
label Public logbook
p Would you like your logbook to be public?
-if(user.logPublic){
- logbookVal = true
-}
input(type='checkbox',name='userPublicLogbook',class='floatLeftCheckbox',checked=logbookVal)
Both are set to Boolean in mongoDB. Both are correctly spelled etc.
Result of console.log:
deserializing user: { _id: 5547e77928d405cc236d4a01,
updated_at: 'Mon May 04 2015 17:41:13 GMT-0400 (EDT)',
created_at: 'Mon May 04 2015 17:41:13 GMT-0400 (EDT)',
admin: false,
lastName: '######',
firstName: '######',
email: '######',
password: '######',
callsign: '######',
uid: '$2a$10$/yF1pqR9N5VkXcnLaNDPBea8xH.tO3Tto82W.9wGD3VdZGPAdXID6',
profilePublic: true,
logPublic: true,
__v: 0 }
Also tried:
-if(user.logPublic)
p It's true
Still nothing

Related

How do I format [future, non-current] dates in Eleventy + Nunjucks?

I'm building a site with a CMS (Netlify) for a local band, and they have future gig dates they will put on the site. So far the dates show up as very long non-formatted strings that include the time and time zone. I'm trying to figure out how to format the dates to be simpler (day, date, time for example).
I've tried plugins like nunjucks-date but I'm a little confused about how to use a plugin (and filters) in this case.
My repo: https://github.com/mollycarroll/serapis-eleventy-2
Example gig entry:
---
layout: gig
venue: Cedar Lake Cellars
date: 2022-05-28
time: 6pm
city: Wright City, MO
---
Gig template:
<h2>{{ venue }}</h2>
<h4>{{ city }} {{ date }} {{ time }}</h4>
config.yml for the CMS:
- name: 'gigs'
label: 'Shows'
folder: 'src/gigs'
create: true
slug: '{{month}}-{{day}}-{{venue}}'
fields:
- { label: 'Layout', name: 'layout', widget: 'hidden', default: '_includes/gig.njk' }
- { label: 'Date', name: 'date', widget: 'date', default: '' }
- { label: 'Time', name: 'time', widget: 'string', default: '' }
- { label: 'Venue', name: 'venue', widget: 'string', default: '' }
- { label: 'City', name: 'city', widget: 'string', default: '' }
Thanks for any help.
First, you should create a filter, let's say src/filters/date.js with the following content:
const { DateTime } = require("luxon");
// Add a friendly date filter to nunjucks.
// Defaults to format of LLLL d, y unless an
// alternate is passed as a parameter.
// {{ date | friendlyDate('OPTIONAL FORMAT STRING') }}
// List of supported tokens: https://moment.github.io/luxon/docs/manual/formatting.html#table-of-tokens
module.exports = (dateObj, format = 'LLLL d, y') => {
return DateTime.fromISO(dateObj, { zone: "Europe/Amsterdam", locale: "en" }).toFormat(format);
};
Make sure you check Luxon documentation for details. Then add the filter in .eleventy.js:
module.exports = function(eleventyConfig) {
...
eleventyConfig.addFilter("date", require("./src/filters/date.js"));
...
};
Now you can use it in Nunjacks with a default value {{ date }}, in this example 'LLLL d, y', or any value you need at a certain position on your website {{ date | date('dd. LLLL yyyy.') }}. This can be very useful if you need at some point just month and year or just day and month.
You can even create multiple language filters, like dateEn.js and dateDe.js, and format each to its own language if you have a multilingual site.
Hope this helps.
EDIT: In order for this filter to work the dateObj should be in ISO 8601 format.

Why is ecto raising Ecto.NoPrimaryKeyValueError when I have a primary key and it has a value?

Whenever I run this code:
{:ok, act_1} = %Kempelen.Models.GameAct{}
|> Kempelen.Models.GameAct.changeset(%{
game_play: place_road,
game_player: player_1,
game_round: round_1
})
|> Kempelen.Database.Repo.insert
I'm getting this exception:
** (Ecto.NoPrimaryKeyValueError) struct `%Kempelen.Models.GamePlayer{__meta__: #Ecto.Schema.Metadata<:loaded, "game_players">, account: %Kempelen.Models.Account{__meta__: #Ecto.Schema.Metadata<:loaded, "accounts">, email: "kurtis#difference-engineers.org", game_players: #Ecto.Association.NotLoaded<association :game_players is not loaded>, game_rounds: #Ecto.Association.NotLoaded<association :game_rounds is not loaded>, game_tables: #Ecto.Association.NotLoaded<association :game_tables is not loaded>, id: "65880220-e39b-450d-ba7f-0642bea8dbc8", inserted_at: ~N[2020-02-16 16:15:33], name: nil, onboarding_state: "converted", organization_memberships: #Ecto.Association.NotLoaded<association :organization_memberships is not loaded>, organizations: #Ecto.Association.NotLoaded<association :organizations is not loaded>, password: nil, password_hash: nil, role_state: "user", unconfirmed_email: "kurtis#difference-engineers.org", updated_at: ~N[2020-02-16 16:15:33], username: nil}, account_id: "65880220-e39b-450d-ba7f-0642bea8dbc8", game_acts: #Ecto.Association.NotLoaded<association :game_acts is not loaded>, game_robot: nil, game_robot_id: nil, game_table: %Kempelen.Models.GameTable{__meta__: #Ecto.Schema.Metadata<:loaded, "game_tables">, game: %Kempelen.Models.Game{__meta__: #Ecto.Schema.Metadata<:loaded, "games">, game_plays: #Ecto.Association.NotLoaded<association :game_plays is not loaded>, game_tables: #Ecto.Association.NotLoaded<association :game_tables is not loaded>, id: "31eee3b8-b43c-411a-8528-479269c63d2d", inserted_at: ~N[2020-02-16 16:15:33], name: "Settlers of Catan", organization: %Kempelen.Models.Organization{__meta__: #Ecto.Schema.Metadata<:loaded, "organizations">, accounts: #Ecto.Association.NotLoaded<association :accounts is not loaded>, games: #Ecto.Association.NotLoaded<association :games is not loaded>, id: "3311c337-f480-4292-9582-c45f249730b2", inserted_at: ~N[2020-02-16 16:15:32], name: "Hasbro", organization_memberships: #Ecto.Association.NotLoaded<association :organization_memberships is not loaded>, robots: #Ecto.Association.NotLoaded<association :robots is not loaded>, slug: "hasbro", updated_at: ~N[2020-02-16 16:15:32]}, organization_id: "3311c337-f480-4292-9582-c45f249730b2", slug: "settlers-of-catan", updated_at: ~N[2020-02-16 16:15:33]}, game_id: "31eee3b8-b43c-411a-8528-479269c63d2d", game_players: #Ecto.Association.NotLoaded<association :game_players is not loaded>, game_rounds: #Ecto.Association.NotLoaded<association :game_rounds is not loaded>, id: "2cda5e3c-c57d-4117-a541-0c6a409984b6", inserted_at: ~N[2020-02-16 16:15:33], name: "FFA", slug: "ffa", updated_at: ~N[2020-02-16 16:15:33]}, game_table_id: "2cda5e3c-c57d-4117-a541-0c6a409984b6", host: true, id: "591227e6-3ea0-4f3f-8a44-471d7073c2df", inserted_at: ~N[2020-02-16 16:15:33], name: "Kurtis", slug: "kurtis", updated_at: ~N[2020-02-16 16:15:33]}` is missing primary key value
Here's are the models:
defmodule Kempelen.Models.GameAct do
use Ecto.Schema
import Ecto.Changeset
#primary_key {:id, :binary_id, autogenerate: true}
#foreign_key_type :binary_id
schema "game_acts" do
belongs_to :game_play, Kempelen.Models.GamePlay, primary_key: true
belongs_to :game_player, Kempelen.Models.GamePlayer, primary_key: true
belongs_to :game_round, Kempelen.Models.GameRound, primary_key: true
timestamps()
end
#doc false
def changeset(%{} = record, attributes \\ %{}) do
record
|> cast(attributes, [])
|> validate_required([])
|> assoc_constraint(:game_play)
|> assoc_constraint(:game_player)
|> assoc_constraint(:game_round)
|> put_assoc(:game_play, attributes.game_play)
|> put_assoc(:game_player, attributes.game_player)
|> put_assoc(:game_round, attributes.game_round)
end
end
defmodule Kempelen.Models.GamePlayer do
use Ecto.Schema
import Ecto.Changeset
#primary_key {:id, :binary_id, autogenerate: true}
#foreign_key_type :binary_id
schema "game_players" do
field :name, :string
field :slug, Kempelen.Slugs.Name.Type
field :host, :boolean, default: false
belongs_to :game_table, Kempelen.Models.GameTable, primary_key: true
belongs_to :account, Kempelen.Models.Account, primary_key: true
belongs_to :game_robot, Kempelen.Models.GameRobot, primary_key: true
has_many :game_acts, Kempelen.Models.GameAct
timestamps()
end
#doc false
def changeset(%{} = record, attributes \\ %{}) do
record
|> cast(attributes, [:name, :host])
|> validate_required([:name, :host])
|> assoc_constraint(:game_table)
|> assoc_constraint(:account)
|> assoc_constraint(:game_robot)
|> Kempelen.Slugs.Name.maybe_generate_slug
|> Kempelen.Slugs.Name.unique_constraint
|> put_assoc(:game_robot, attributes[:game_robot])
|> put_assoc(:account, attributes[:account])
|> put_assoc(:game_table, attributes.game_table)
end
end
It's not just the game_play model either, it also happens of the game_player.
The changeset appears to think it's valid, as well:
#Ecto.Changeset<
action: nil,
changes: %{
game_play: #Ecto.Changeset<action: :update, changes: %{}, errors: [],
data: #Kempelen.Models.GamePlay<>, valid?: true>,
game_player: #Ecto.Changeset<action: :update, changes: %{}, errors: [],
data: #Kempelen.Models.GamePlayer<>, valid?: true>,
game_round: #Ecto.Changeset<action: :update, changes: %{}, errors: [],
data: #Kempelen.Models.GameRound<>, valid?: true>
},
errors: [],
data: #Kempelen.Models.GameAct<>,
valid?: true
>
Alright, so I finally figured it out. It turns out that while I wanted the account and game_robot relationships to be optional (one or the other, in business logic), the primary_key: true option for belongs_to in the schema means that the foreign key column must have a value.

Mongoose: moment().format not working

Im having Mongoose schema as follows:
createdOn: {
type: String,
//default: Date.now,
default: moment(new Date(Date.now())).format('MMM Do YY') //npm install moment --save # npm
},
updatedOn: {
type: String,
//default: Date.now
default: moment(new Date(Date.now())).format('MMM Do YY')
}
UPDATE:
After changing the type to String,
I get :
Fri Jul 28 2017 14:43:40 GMT+0530 (IST)
How to remove the time and SMT.
I need to keep only Fri Jul 28 2017
I installed Moment package of node js (http://momentjs.com/)
Whats wrong in my schema above:
I get
MongooseError: Cast to date failed for value "Aug 7th 17" at path "updatedOn"
message: 'Cast to date failed for value "Aug 7th 17" at path "updatedOn"',
name: 'CastError',
stringValue: '"Aug 7th 17"',
kind: 'date',
value: 'Aug 7th 17',
path: 'updatedOn',
reason: undefined }
The double default assignment looks wrong.
default: default: moment(new Date(Date.now())).format('MMM Do YY')
As a better practice, you should consider just using UNIX timestamps rather than formatted date strings. Timestamps will allow you to easily track statistics on the database.
So you could just use the:
Date.now() // returns a UNIX timestamp
In moment.js a UNIX timestamp:
moment().unix()
If for some reason you need the timestamp in a string format you could always just do:
moment().unix() + ''

Rails Mongoid search parents elements that have at least one child

I have a rails 4 app and I have 2 objects: stores and books (referenced 1:n relation).
A store has many books, each book belongs to one store. Some stores don't have any books.
How can I make a query to find the 3 latest store that has at least 1 book - and the 3 latest stores that have no books ?
#stores = Store.order_by(:created_at => 'desc').limit(4).uniq
#books = Book.order_by(:created_at => 'desc').limit(4).uniq
This work but I don't know how to do a where(book.exists?) for store, or for the #books to make sure each book belongs to a unique store.
Basic CRUD operations in MongoDB operate on a single collection,
"join" capability is not yet implemented that would allow them to operate across two collections.
Once you understand this, you can easily construct two operations that will do what you want.
The following is the most obvious given the schema hints that you supplied.
To do anything more, you probably want to consider schema changes like embedding.
By definition, your supplied schema only allows a book to belong to one (unique by definition) store.
You can see this from the inspection of the books, that there is a single value store_id for each book.
Hope that this helps your understanding.
app/models/store.rb
class Store
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
has_many :books
end
app/models/book.rb
class Book
include Mongoid::Document
include Mongoid::Timestamps
field :title, type: String
belongs_to :store
end
test/unit/store_test.rb
require 'test_helper'
require 'pp'
class StoreTest < ActiveSupport::TestCase
def setup
Mongoid.default_session.drop
end
test '0. mongoid version' do
puts "\nMongoid::VERSION:#{Mongoid::VERSION}\nMoped::VERSION:#{Moped::VERSION}"
end
test 'store query has book, does not have book' do
[
["Amazon.com", ["Outlander", "Taking It All"]],
["Barnes & Noble", ["Big Little Lies"]],
["Goodreads", []],
["Greenlight Bookstore", []],
["Powell's Books", ["Gone Girl", "Dark Skye"]],
["Strand Books", []]
].each do |store, books|
store = Store.create(name: store)
books.each do |title|
store.books << Book.create(title: title)
end
sleep 1
end
assert_equal(6, Store.count)
assert_equal(5, Book.count)
puts
store_ids_with_books = Book.distinct(:store_id)
latest_stores_with_a_book = Store.in(_id: store_ids_with_books).order_by(:created_at => 'desc').limit(3).to_a
puts "three latest stores with a book:"
pp latest_stores_with_a_book
latest_stores_without_a_book = Store.nin(_id: store_ids_with_books).order_by(:created_at => 'desc').limit(3).to_a
puts "three latest stores without a book:"
pp latest_stores_without_a_book
puts "books:"
pp Book.all.to_a
end
end
rake test
Run options:
# Running tests:
[1/2] StoreTest#test_0._mongoid_version
Mongoid::VERSION:3.1.6
Moped::VERSION:1.5.2
[2/2] StoreTest#test_store_query_has_book,_does_not_have_book
three latest stores with a book:
[#<Store _id: 53f257287f11ba75e5000008, created_at: 2014-08-18 19:42:32 UTC, updated_at: 2014-08-18 19:42:32 UTC, name: "Powell's Books">,
#<Store _id: 53f257257f11ba75e5000004, created_at: 2014-08-18 19:42:29 UTC, updated_at: 2014-08-18 19:42:29 UTC, name: "Barnes & Noble">,
#<Store _id: 53f257247f11ba75e5000001, created_at: 2014-08-18 19:42:27 UTC, updated_at: 2014-08-18 19:42:27 UTC, name: "Amazon.com">]
three latest stores without a book:
[#<Store _id: 53f257297f11ba75e500000b, created_at: 2014-08-18 19:42:33 UTC, updated_at: 2014-08-18 19:42:33 UTC, name: "Strand Books">,
#<Store _id: 53f257277f11ba75e5000007, created_at: 2014-08-18 19:42:31 UTC, updated_at: 2014-08-18 19:42:31 UTC, name: "Greenlight Bookstore">,
#<Store _id: 53f257267f11ba75e5000006, created_at: 2014-08-18 19:42:30 UTC, updated_at: 2014-08-18 19:42:30 UTC, name: "Goodreads">]
books:
[#<Book _id: 53f257247f11ba75e5000002, created_at: 2014-08-18 19:42:28 UTC, updated_at: 2014-08-18 19:42:28 UTC, title: "Outlander", store_id: "53f257247f11ba75e5000001">,
#<Book _id: 53f257247f11ba75e5000003, created_at: 2014-08-18 19:42:28 UTC, updated_at: 2014-08-18 19:42:28 UTC, title: "Taking It All", store_id: "53f257247f11ba75e5000001">,
#<Book _id: 53f257257f11ba75e5000005, created_at: 2014-08-18 19:42:29 UTC, updated_at: 2014-08-18 19:42:29 UTC, title: "Big Little Lies", store_id: "53f257257f11ba75e5000004">,
#<Book _id: 53f257287f11ba75e5000009, created_at: 2014-08-18 19:42:32 UTC, updated_at: 2014-08-18 19:42:32 UTC, title: "Gone Girl", store_id: "53f257287f11ba75e5000008">,
#<Book _id: 53f257287f11ba75e500000a, created_at: 2014-08-18 19:42:32 UTC, updated_at: 2014-08-18 19:42:32 UTC, title: "Dark Skye", store_id: "53f257287f11ba75e5000008">]
Finished tests in 6.193234s, 0.3229 tests/s, 0.3229 assertions/s.
2 tests, 2 assertions, 0 failures, 0 errors, 0 skips

Why does my gridPanel in a tabPanel show the wrong height?

In the attached image, the grid does not show properly. The grid is inside a tabpanel. The layout of the tab is = 'fit'.
What setting error is causing the behavior?
EDIT:
Here is the class definition for the tabpanel: Our tab is the one called 'External ID'
/*
* File: SomeTabPanel.ui.js
* Date: Mon May 02 2011 18:08:34 GMT-0400 (Eastern Daylight Time)
*
* This file was generated by Ext Designer version xds-1.0.3.2.
* http://www.extjs.com/products/designer/
*
* This file will be auto-generated each and everytime you export.
*
* Do NOT hand edit this file.
*/
SomeTabPanelUi = Ext.extend(Ext.TabPanel, {
activeTab: 0,
forceLayout: true,
border: false,
enableTabScroll: true,
initComponent: function() {
this.items = [{
xtype: 'panel',
title: 'General',
layout: 'table',
tpl: '',
ref: 'GeneralTab',
layoutConfig: {
columns: 2
},
items: [{
xtype: 'form',
title: 'Corporate',
height: 500,
width: 500,
animCollapse: false,
items: [{
xtype: 'box',
ref: '../../coporateBox'
}]
}]
},{
xtype: 'panel',
title: 'External ID',
layout: 'fit',
ref: 'ExtIdTab',
id: ''
}];
SomeTabPanelUi.superclass.initComponent.call(this);
}
});
Looks like you need to set a height for the grid somehow. Either a manual height declaration, autoHeight: true, or inherited height from a parent container.
Does the parent tabPanel have a height declared/inherited?
Setting layout: 'fit' is a good start for the containing tab, but without some code or a test case, I can't be more helpful.
It should work as described, so you must have something wrong in your code. Post your layout code if you want more help.

Resources