RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-220221

Sergei R's questions

Martin Hope
Sergei R
Asked: 2020-05-25 02:26:40 +0000 UTC

Vue.js - 如何将数据返回到父组件?

  • 2

我有一个父组件,在 data() 中我想从子组件传递一个计算属性。

// ParentComponent.vue
<template>
  <div>
    <ChildComponent :parent="parent"/>
  </div>
</template>

<script>
import ChildComponent from '@/components/ChildComponent';

export default {
  name: 'ParentComponent',
  components: {
    ChildComponent,
  },
  data() {
    return {
      parent: {
        parentData: '',
      }
    };
  },
</script>

在子组件中,计算属性是字符串的串联,子组件的数据属性的字段。

<template>
  <div>
    <div class="control">
      <input
        v-model="salarySumm"
        class="input"
        type="text"
        placeholder="Add the estimated salary (1000 - 2000)"
      >
      <div class="select">
        <select v-model="salaryCode">
          <option disabled value>Select currency</option>
          <option
            v-for="(el, index) in currency"
            :key="index"
            :value="el.code"
          >{{ el.title }}</option>
        </select>
      </div>
  </div>
</template>

<script>  
export default {
  name: 'ChildComponent',
  props: ['parent'],
  data() {
    return {
      salarySumm: '',
      salaryCode: '',
    }
  },
  created() {
    // Тут я получаю массив объектов в виде 
    // [{ title: 'string', code: 'string' }]
    this.$store.dispatch('getCurrencies')
  },
  computed: {
    currency() {
      let list = this.$store.getters.currencies.data
      const currencyList = []
      if (list !== undefined) {
        for (const el of list) {
          if (el.code == '(none)' || el.code == null) el.code = ''
          if (el.name !== null) {
            currencyList.push({ title: `${el.name} | ${el.code}`, code: el.code })
          }
        }
      }
      return currencyList
    },
    salary() {
      // Здесь я получаю строку в том виде, в котором хочу передать ее в родительский компонент.
      return this.salarySumm + ' ' + this.salaryCode
    },
</script>

如何将计算的属性薪水传递给父组件,更具体地说是 parent.parentData?

javascript
  • 2 个回答
  • 10 Views
Martin Hope
Sergei R
Asked: 2020-04-13 16:15:21 +0000 UTC

从 Spring Boot 连接到 H2 数据库

  • 0

我正在尝试连接到 H2 数据库。我正在使用 Spring Boot。

pom.xml

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

应用程序属性

# DataSource settings: set here your own configurations for the database
spring.datasource.url=jdbc:h2:tcp://localhost/~/villagebank
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create

# H2 settings
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

我打开http://localhost:8090/h2它,我进入登录页面,我按下Test connection它,我得到一个错误。

在此处输入图像描述

如何解决这个问题呢?我试图去首选项,但我需要一个管理员密码,我没有,我在谷歌搜索它并没有找到任何信息。因此,我在应用程序中执行的所有其他操作也会导致错误。

IDEA中的H2连接画面

在此处输入图像描述

java
  • 1 个回答
  • 10 Views
Martin Hope
Sergei R
Asked: 2020-01-25 03:09:42 +0000 UTC

Mongoose:如何等待与数据库的连接,然后执行以下操作?

  • 0

我需要制作一个必须连接到数据库的控制台应用程序,然后在屏幕上显示一个菜单以选择进一步的操作。

index.js

// Set connection from DB
require('./src/services/db')

const messages = require('./src/services/messages')

console.log(messages.start())

数据库.js

const mongoose = require('mongoose')
const { mongodbUri } = require('../config/config')

// log to console
mongoose.set('debug', true)

mongoose.connect(mongodbUri.mlab, { useNewUrlParser: true })

mongoose.connection.on('error', (e) => {
  console.log(`MongoDB connection error: ${e}`)
})
mongoose.connection.once('open', () => console.log('Connected to MongoDB'))
mongoose.connection.on('disconnected', () => console.log('Disconnected from MongoDB'))

module.exports = {
  connection: mongoose.connection,
}

结果,我得到了这张图片

在此处输入图像描述

在调用 messages.start() 之前,我需要连接到 MongoDB 日志

我知道我需要使用 await / async,但我不明白在这种情况下如何应用它。

javascript
  • 1 个回答
  • 10 Views
Martin Hope
Sergei R
Asked: 2020-11-29 11:31:30 +0000 UTC

Vue.js如何包含第三方materializecss库?

  • 0

我想在我的项目中使用materializecss库而不是 vue-material

您可以将其包含在索引文件中,如下所示:

<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

好吧,据我了解,这不是正确的做法,虽然我为什么不明白,你也可以澄清一下。

您可以通过 npm 安装并创建一个插件:

./src/plugins/materializecss.js

import 'materialize-css/dist/js/materialize.min.js'
import 'materialize-css/dist/css/materialize.min.css'

./src/main.js

// Тут я пробовал и так ...
import '@/plugins/materializecss'

// ... и так
import M from 'materialize-css' 
Vue.use(M)

因为在这篇文章中

import './../node_modules/jquery/dist/jquery.min.js'
import './../node_modules/materialize-css/dist/css/materialize.min.css'
import './../node_modules/materialize-css/dist/js/materialize.min.js'

结果有样式,但是js不行。

./src/App.vue 插入下拉菜单

<template>
  ...
  <div>
    <!-- Dropdown Trigger -->
    <a class='dropdown-trigger btn' href='#' data-target='dropdown1'>Drop Me!</a>

    <!-- Dropdown Structure -->
    <ul id='dropdown1' class='dropdown-content'>
      <li><a href="#!">one</a></li>
      <li><a href="#!">two</a></li>
      <li class="divider" tabindex="-1"></li>
      <li><a href="#!">three</a></li>
      <li><a href="#!"><i class="material-icons">view_module</i>four</a></li>
      <li><a href="#!"><i class="material-icons">cloud</i>five</a></li>
    </ul>
  </div>
  ....
</template>

如何正确连接此类第三方库/框架?

vue.js
  • 1 个回答
  • 10 Views
Martin Hope
Sergei R
Asked: 2020-11-01 04:52:56 +0000 UTC

如果字段具有有效值,角度材料如何手动将字段标记为无效(并将其重新着色为红色)

  • 0

注册表单,字段被填写并发送到服务器。服务器发送电子邮件已忙的响应。然后我想将电子邮件字段突出显示为无效,但该字段中的值支持电子邮件格式并被验证器识别为有效。

在此处输入图像描述

尝试了不同的变化

this.registerForm.controls['email'].setErrors({ invalid: true, valid: false })

但该领域没有着色。怎么做?

注册.component.ts

export class RegistrationComponent implements OnInit {

  public registerForm: FormGroup
  public spinnerShow = false
  public errMsg: String
  public bothErrMsg: String.

  constructor(
    ...
    private matDialogRef: MatDialogRef<RegistrationComponent>,
    private fb: FormBuilder
  ) {}

  ngOnInit() {
    this.registerForm = this.fb.group({
      email: ['', [FormValidationService.emailValidator]],
      password: this.fb.group({
        pwd: ['', [FormValidationService.passwordValidator]],
        confirm: ['', [FormValidationService.passwordValidator]],
      }, {validator: FormValidationService.confirmValidator('pwd', 'confirm')}),
      username: ['', [FormValidationService.shortStringValidator]],
    })
  }

  register() {
    this.spinnerShow = !this.spinnerShow
    const regData = this.registerForm.value
    regData.confirm = this.registerForm.value.password.confirm
    regData.password = this.registerForm.value.password.pwd

    this.auth.registration(regData).subscribe(
      (res: any) => {
        if (res.error) {
          this.spinnerShow = !this.spinnerShow
          const messages = res.messages
          for (const key in messages) {
            if (messages.hasOwnProperty(key)) {
              if (key === 'both') {
                this.bothErrMsg = messages[key]
                this.registerForm.controls['email'].setErrors({ notUnique: true })
              } else {
                this.registerForm.controls[key].setErrors({ errMsg: messages[key] })
              }
            }
          }
        } else {
          this.lc.setItem('user', res.user)
          this.matDialogRef.close()
        }
      },
      error => {
        console.log(error) // TODO
        this.spinnerShow = !this.spinnerShow
      }
    )
  }
}

注册.component.html

<div class="container">
  <h3>Register new user.</h3>
  <form [formGroup]="registerForm" novalidate>
    <mat-form-field>
      <input matInput formControlName="email" placeholder="Email" type="email" required>
      <mat-error *ngIf="registerForm.controls.email.hasError('errMsg') && registerForm.controls.email.touched">
        {{ registerForm.get('email').getError('errMsg') }}
      </mat-error>
    </mat-form-field>

    <div class="error" *ngIf="bothErrMsg !== undefined">{{ bothErrMsg }}</div>

    <button mat-raised-button color="primary" [disabled]="registerForm.invalid == true" (click)="register()">Sign Up</button>
  </form>
</div>

来自服务器的错误(两者都是 serverErrorMsg 尚未重命名为正常名称)。服务器返回 200 代码和错误消息(如果有)。 在此处输入图像描述

angular4
  • 1 个回答
  • 10 Views
Martin Hope
Sergei R
Asked: 2020-11-03 15:32:48 +0000 UTC

woocommerce where 产品图像模板钩 woocommerce_template_loop_product_thumbnail

  • 1

我需要更改用于显示产品图像的模板、包装器 (HTML img)。文件中的woocommerce_before_shop_loop_item挂钩 负责显示图像。

/wp-content/plugins/woocommerce/templates/content-product.php

钩子调用woocommerce_get_product_thumbnail函数

wp-content/plugins/woocommerce/includes/wc-template-functions.php

然后我迷路了。

挂钩将图片包裹在里面

<img class="...

这是包装图片的html模板,我需要更改它。

更新

根据下面的答案,我在这里做了一个函数 my-theme/woocommerce/function.php

function filter_woocommerce_product_get_image( $image, $_this, $size, $attr, $placeholder ) {
  if ( has_post_thumbnail( $_this->get_id() ) ) {
            $image = get_the_post_thumbnail( $_this->get_id(), $size, $attr );
    } elseif ( ( $parent_id = wp_get_post_parent_id( $_this->get_id() ) ) && has_post_thumbnail( $parent_id ) ) {
            $image = get_the_post_thumbnail( $parent_id, $size, $attr );
    } elseif ( $placeholder ) {
            $image = custom_wc_placeholder_img( $size );
    } else {
            $image = '';
    }

  return $image;
}

add_filter ( 'woocommerce_product_get_image', 'filter_woocommerce_product_get_image', 10, 5);

我在 content-product.php 中调用了钩子

do_action( 'woocommerce_product_get_image' );

得到

致命错误:未捕获的 ArgumentCountError:函数 filter_woocommerce_product_get_image() 的参数太少

wordpress
  • 2 个回答
  • 10 Views
Martin Hope
Sergei R
Asked: 2020-10-31 00:53:43 +0000 UTC

不在 Storefront 模板的子主题中添加第三方样式

  • 0

按照说明为 Storefront 制作了一个子主题。

样式和脚本包含在/wp-content/themes/storefront/inc/class-storefront.php文件中。(第 204 行)

我需要添加我的样式,例如引导程序,我将 class-storefront.php 文件复制到我的主题 /wp-content/themes/mytheme/inc/class-storefront.php 并只保留函数

public function scripts() {
  global $storefront_version;

  /**
  * Styles
  */
  wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/assets/css/bootstrap.min.css', array("storefront-style") );
}

头中的引导程序未连接,将其放入 /wp-content/themes/storefront/assets/css/bootstrap.min.css 和 /wp-content/themes/mytheme/assets/css/bootstrap.min.css 无论如何都没有连接。

我的 class-storefront.php 有什么问题?

wordpress
  • 1 个回答
  • 10 Views
Martin Hope
Sergei R
Asked: 2020-10-28 14:38:20 +0000 UTC

如何添加和编辑本地化翻译

  • 0

我需要为 woocommerce 主题添加翻译字符串。我在这里找到了他的翻译文件/wp-content/languages/plugins/。主题有自己的文件夹 /wp-content/themes/mytheme/languages/

如果您在 /wp-content/languages/plugins/ 中编辑翻译,更新插件时翻译会丢失吗?

或者如何将翻译添加到 /wp-content/themes/mytheme/languages/ 并将它们用于 woocommerce 插件翻译(插件功能)?

这些方法中哪一种更正确,在我看来有点像第二种方法。

我知道 poedit,我自己现在使用 Loco Translate 并想继续。

wordpress
  • 2 个回答
  • 10 Views
Martin Hope
Sergei R
Asked: 2020-10-05 22:45:48 +0000 UTC

如何使按钮的水平列表缩放以适应不同的屏幕?

  • 0

我制作了一个片段,其中 4 个按钮以菜单的形式水平放置。看起来像这样:

在此处输入图像描述

编码:

<Button
    android:id="@+id/button"
    android:layout_width="86dp"
    android:layout_height="50dp"
    android:layout_marginLeft="5dp"
    android:layout_marginTop="0dp"
    android:text="button1"
    android:textSize="10sp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button2"
    android:layout_width="86dp"
    android:layout_height="50dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="0dp"
    android:text="button2"
    android:textSize="10sp"
    app:layout_constraintLeft_toRightOf="@+id/button"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button3"
    android:layout_width="86dp"
    android:layout_height="50dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="0dp"
    android:text="button3"
    android:textSize="10sp"
    app:layout_constraintLeft_toRightOf="@+id/button2"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button4"
    android:layout_width="86dp"
    android:layout_height="50dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginTop="0dp"
    android:text="button4"
    android:textSize="10sp"
    app:layout_constraintLeft_toRightOf="@+id/button3"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

我启动模拟器并看到这张图片:

在此处输入图像描述

如何让它在一行中出现在不同的屏幕上?

android
  • 1 个回答
  • 10 Views
Martin Hope
Sergei R
Asked: 2020-05-29 23:03:52 +0000 UTC

您需要解析一个依赖于父元素的数组

  • 0

有一个数据对象,您需要解析它,记下每个 id 及其父对象。

我的版本:

const object = {"id":"1","sub_id":[{"id":"1.1","sub_id":[{"id":"1.1.1"},{"id":"1.1.2"},{"id":"1.1.3"}]},{"id":"1.2","sub_id":[{"id":"1.2.1"},{"id":"1.2.2"},{"id":"1.2.3"},{"id":"1.2.4","sub_id":[{"id":"1.2.4.1"}]}]}]};

let data = object;
let relation = undefined;

function objectParsing(data) {
    if (data["sub_id"] != undefined) {

        for (let key in data) {
            if (key == 'id') {
                console.log('Create new id: ' + data[key]);
                if (relation != undefined) {
                    console.log('Create parent: ' + relation + '_id for id: ' + data[key]);
                    relation = data[key];
                    console.log('Store new relation: ', relation);
                } else {
                    relation = data[key];
                }
            }
            if (key == 'sub_id') {
                data[key].forEach(function (item, i, arr) {
                    objectParsing(item);
                });
            }
        }

    } else {
        for (let key in data) {
            console.log('Create new id: ' + data[key]);
            if (relation != undefined) {
                console.log('Create relation: ' + relation + '_id for id: ' + data[key]);
            }
        }
    }
}

objectParsing(data);

控制台输出:

Create new id: 1
Create new id: 1.1
Create parent: 1_id for id: 1.1
Store new relation:  1.1
Create new id: 1.1.1
Create relation: 1.1_id for id: 1.1.1
Create new id: 1.1.2
Create relation: 1.1_id for id: 1.1.2
Create new id: 1.1.3
Create relation: 1.1_id for id: 1.1.3
Create new id: 1.2
Create parent: 1.1_id for id: 1.2 // проблема тут
Store new relation:  1.2
Create new id: 1.2.1
Create relation: 1.2_id for id: 1.2.1
Create new id: 1.2.2
Create relation: 1.2_id for id: 1.2.2
Create new id: 1.2.3
Create relation: 1.2_id for id: 1.2.3
Create new id: 1.2.4
Create parent: 1.2_id for id: 1.2.4
Store new relation:  1.2.4
Create new id: 1.2.4.1
Create relation: 1.2.4_id for id: 1.2.4.1

对于id 1.2我覆盖的依赖id 1——帮助修正,考虑到对象的深度可以有条件地无限,同时可能有更优化的方式。

javascript
  • 1 个回答
  • 10 Views
Martin Hope
Sergei R
Asked: 2020-05-23 04:50:33 +0000 UTC

需要一种算法来比较数组中的数据级别

  • 0

有一个带有亲戚的对象,它们按类型相互关联:Parent,Child,Brother / Sister,Equal

{
"parent": "Bill",
"parent": "Anna",
"children": [
    {
    "parent": "Mark",
    "parent": "Sara",
    "children": [
            { "parent": "Sofia" },
            { "parent": "Patric" },
            { "parent": "Marta" }
    ]}
]}

数据库有表:

Peoples (id, name);
References (ENUM(parent, children, sibling), тут видимо надо будет дополнить);

如何设置它们之间的家庭关系,使其看起来像这样: 如果我对 Anna 进行数据库查询,我得到:

"sibling": Bill,
"children": Mark,
"children": Sara,

如果我对 Marta 进行数据库查询,我会得到:

"parent": Mark,
"parent": Sara,
"sibling": Sofia,
"sibling": Patric,
"sibling": Marta,

问题不在于如何提出要求,而在于如何比较他们之间的关系,分配相对于彼此的角色。

例如,我们获取 Bill 和 Anna,查看它们在同一级别上的含义 Bill for Anna -> sibling 反之亦然,并将这些关系写入数据库。

例如,我们得到 Mark 和 Anna,我们看到 Mark 比 Anna 低一个级别,所以 Anna 对 Mark 有一个级别 -> parent,而 Mark 对 Anna 有一个级别 -> children 并将这些关系写入数据库。

附言 我们不会挑剔家庭关系的不准确之处。

javascript
  • 1 个回答
  • 10 Views
Martin Hope
Sergei R
Asked: 2020-05-16 03:08:48 +0000 UTC

如何获得一个月的第一天和最后一天?时区偏移问题

  • 0

我需要以 YYYY.MM.DD.HH.MM.SS 格式获取月份的开始和结束,格式作为时间精度的示例。

let dateNow = new Date(); //2017-05-15T17:00:37.982Z

let getYear = dateNow.getFullYear(); //2017
let getMonth = dateNow.getMonth(); //4 т.к. месяцы с нуля то все ок

let startDate = new Date(getYear, getMonth, 1); 
//2017-04-30T21:00:00.000Z идет сдвиг месяца на -1, число 30 вместо 1, часы 21

let stopDate = new Date(getYear, getMonth, 0, 23, 59, 59); 
//2017-04-30T20:59:59.000Z идет сдвиг месяца на -1 часа на -3

目前尚不清楚这个月发生了什么,为什么变成了四月以及随着时间的推移。我阅读了有关 UTC 的信息,但如果用户来自不同时区怎么办?

javascript
  • 1 个回答
  • 10 Views
Martin Hope
Sergei R
Asked: 2020-04-21 23:24:29 +0000 UTC

node.js 承诺,未完全理解的承诺 [重复]

  • 0
这个问题已经在这里得到回答:
$q.all 不会等到所有承诺都已解决 (2 个答案)
5 年前关闭。

好像明白了原理,但实际上并不是一帆风顺。

首先.js

const getVisa = require('./second.js');
function queryForVisa() {
    console.log('Query processing ...... --------');
    let promise = new Promise(function(resolve, reject) {
        setTimeout(function() {
            let allowed = true;
            if(allowed) {
                console.log('Visa is allowed');
                resolve();
            } else {
                reject('The visa is denied');
            }
        }, 2000);
    });
    return promise;
}

queryForVisa()
    .then(getVisa) // этот срабатывает правильно, ждет промиса и тогда начинает выполняться
    .then(function(data) { //этот не дожидается промиса и выполняется
        console.log('last then');
        console.log(data);
    })
    .catch(error => console.log(error));

第二.js

const getVisa = function () {
        setTimeout(function() {
            console.log('Visa received');
            let travel = {};
            let visa = {
                country: 'USA'
            }
            travel.visa = visa;
            console.log('getVisa.visa', visa);
            return Promise.resolve(travel);
        }, 2500);
    }

module.exports = getVisa;

和响应日志:

Query processing ...... --------
Visa allowed
last then
undefined
Visa received
getVisa.visa { country: 'USA' }

我知道第二个功能有问题,但是什么?也有必要按照queryForVisa的形象做新的Promise吗?我在github和教程上看别人的代码,那里一切都很简单:

function()
.then(function(){...})
.then(function(){...})

并且里面没有新的 Promise,return promise。

javascript
  • 1 个回答
  • 10 Views
Martin Hope
Sergei R
Asked: 2020-04-06 11:56:29 +0000 UTC

node.js 在获取请求时得到错误的响应

  • 1

客户端发送请求以获取整个列表,而不是列表或错误,我得到响应:

Object {data: "<!DOCTYPE html>
↵<html lang="en" class="no-js">
↵<…
↵<!--</div>-->
↵<!--</div>-->
↵<!--</div>-->
↵
↵", status: 200, config: Object, statusText: "OK"}

服务器端:

//Find all orders by username
    app.get('/api/orders', function (req, res) {
        //пробовал и тут брейкпоинт, дебагет тут не проходит.
        authorize(req).then(function (foundUser) {
            db.orders.findAll({where: {userId: foundUser.id}})
                .then(function (orders) {
                    res.json({message: 'OKk', body: orders});
                });
        }), function (err) {
            res.status(200).send('User not found');
        }
    });

在同一个控制器中有一个创建订单的方法

//Add new order
    app.post('/api/order', function (req, res) {
        authorize(req).then(function (foundUser) {
            var newOrder = {};
            newOrder.startDate = req.body.startDate;
            newOrder.stopDate = req.body.stopDate;
            newOrder.price = 1;
            newOrder.totalPrice = 100;
            newOrder.userId = foundUser.id;
            db.orders.create(newOrder).then(function (order) {
                db.orders.findAll({where: {userId: foundUser.id}})
                    .then(function (orders) {
                        var ordersList = [];
                        orders.forEach(function (item, i, arr) {
                            var order = {};
                            order.id = item['id'];
                            order.startDate = item['startDate'];
                            order.stopDate = item['stopDate'];
                            order.price = item['price'];
                            order.totalPrice = item['totalPrice'];
                            ordersList.push(order);
                        })
                        res.json({message: 'order added', body: ordersList});
                    });
            });
        }), function (err) {
            res.status(200).send('User not found');
        }
    })

该方法有效,并创建了一个新订单,然后我得到了所有订单。可能是什么问题呢?

OrderController.js 控制器的完整视图


顾客要求:

$scope.url = 'http://localhost:3000/api/';
$scope.getAllOrders = function () {
                $http({
                    method: 'GET',
                    url: $scope.url + 'orders',
                }).then(function success(res) {
                    if (res.data.message == 'OK') {
                        $scope.orders = res.data.body;
                    }
                })
            }

附录:

我尝试访问一个不存在的路径

$scope.getAllOrders = function () {
                    $http({
                        method: 'GET',
                        url: $scope.url + 'ordersghjkhg',

我从服务器得到了相同的响应,所以问题很可能出在主server.js文件中

我在 server.js 中注释掉之后

 app.get('*', function (req,res) {
     res.render('./index.html');
 });

GET 方法开始访问所需的方法 app.get('/api/orders ,但我需要注释掉的路由(或者我不知道如何准确命名它)以便 Angular ui-router 正常工作,而无需它,除索引之外的任何页面在重新加载时返回 404。

javascript
  • 1 个回答
  • 10 Views
Martin Hope
Sergei R
Asked: 2020-03-19 17:00:07 +0000 UTC

Sequelize 在创建迁移时创建一个空模板

  • 0

我已经完成了2个模型

带有字段的用户和订单

当我创建迁移文件时

续集迁移:创建 --name="create_users_and_orders"

我收到一个文件

新迁移创建于 20170319085303-create_users_and_orders.js

'use strict';

module.exports = {
  up: function (queryInterface, Sequelize) {
    /*
      Add altering commands here.
      Return a promise to correctly handle asynchronicity.

      Example:
      return queryInterface.createTable('users', { id: Sequelize.INTEGER });
    */
  },

  down: function (queryInterface, Sequelize) {
    /*
      Add reverting commands here.
      Return a promise to correctly handle asynchronicity.

      Example:
      return queryInterface.dropTable('users');
    */
  }
};

而且我必须自己创建字段,那为什么我们需要生成迁移?我可以自己创建一个简单的文件。

javascript
  • 2 个回答
  • 10 Views
Martin Hope
Sergei R
Asked: 2020-03-04 21:21:38 +0000 UTC

基础迁移到 Heroku

  • 0

ruby on rails中有一个应用

模式.rb

ActiveRecord::Schema.define(version: 20170302072830) do

create_table "stocks", force: :cascade do |t|
  t.string   "name",       null: false
  t.integer  "unit_price", null: false
  t.integer  "interest",   null: false
  t.integer  "duration",   null: false
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.integer  "user_id"
  t.index ["user_id"], name: "index_stocks_on_user_id", using: :btree
end

create_table "users", force: :cascade do |t|
  t.string   "email",               default: "", null: false
  t.string   "encrypted_password",  default: "", null: false
  t.string   "username",            default: "", null: false
  t.datetime "remember_created_at"
  t.integer  "sign_in_count",       default: 0,  null: false
  t.datetime "current_sign_in_at"
  t.datetime "last_sign_in_at"
  t.string   "current_sign_in_ip"
  t.string   "last_sign_in_ip"
  t.datetime "created_at",                       null: false
  t.datetime "updated_at",                       null: false
  t.index ["email"], name: "index_users_on_email", unique: true, using: :btree
end
end

开发过程中有几次迁移

在此处输入图像描述

迁移到 Heroku heroku rake db:migrate

我得到一个日志

在此处输入图像描述

持续时间字段及其整数类型如何?类型从日期更改为整数。

ALTER TABLE "stocks" ALTER COLUMN "duration" TYPE integer PG::DatatypeMismatch: ERROR: column "duration" cannot be cast automatically to type integer

好吧,他的暗示并没有告诉我任何事情。

提示:您可能需要指定“USING duration::integer”。

ruby-on-rails
  • 2 个回答
  • 10 Views
Martin Hope
Sergei R
Asked: 2020-03-04 17:30:20 +0000 UTC

rails如何连接PostgreSQL数据库

  • 1

没有提供带有 sqlite3 数据传输的现成应用程序。您需要连接 PostgreSQL,创建新数据库并进行迁移。安装了 PostgreSQL。创建了一个用户

$ sudo -u postgres psql
postgres-# CREATE ROLE pguser LOGIN ENCRYPTED PASSWORD 'passwd' NOSUPERUSER NOINHERIT CREATEDB NOCREATEROLE;

我看看 pgAdmin

在此处输入图像描述

我去 database.yml

development:
pool: 5
timeout: 5000
adapter: postgresql
database: newdb
username: pguser
password: passwd

自然 gem pg 成本。

我运行 db:create 或 db:setup

$ rake db:setup
FATAL:  Peer authentication failed for user "pguser"
Couldn't create database for {...}

添加了 pg_hba.conf

在此处输入图像描述

ruby-on-rails
  • 1 个回答
  • 10 Views
Martin Hope
Sergei R
Asked: 2020-03-02 01:41:44 +0000 UTC

Rails SQLite3::ConstraintException:唯一约束失败:索引'index_users_on_reset_password_token'

  • 3

我用设计注册

为用户添加了用户名字段。对于授权,我使用电子邮件+密码。

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys:[:username])
  end
end

class User < ApplicationRecord
  validates :username, presence: true
  devise :database_authenticatable, 
     :registerable,
     :rememberable, 
     :trackable, 
     :validatable
end

ActiveRecord::Schema.define(version: 20170228132910) do
  create_table "users", force: :cascade do |t|
    t.string   "email",               default: "", null: false
    t.string   "encrypted_password",  default: "", null: false
    t.string   "username",            default: "", null: false
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",       default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at",                       null: false
    t.datetime "updated_at",                       null: false
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index [nil], name: "index_users_on_reset_password_token", unique: true
  end

end

第一个用户正常注册,第二个我收到错误

ActiveRecord::RecordNotUnique in Devise::RegistrationsController#create SQLite3::ConstraintException: UNIQUE constraint failed: index 'index_users_on_reset_password_token': INSERT INTO "users" ("email", "encrypted_pa​​ssword", "username", "created_at", "updated_at" ) 值 (?, ?, ?, ?, ?)

index_users_on_reset_password_token 有什么问题?

添加迁移

class DeviseCreateUsers < ActiveRecord::Migration[5.0]
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      # Registrable
      t.string :username,           null: false, default: ""

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, default: 0, null: false
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip

      t.timestamps null: false
    end

    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true
  end
end
ruby-on-rails
  • 1 个回答
  • 10 Views
Martin Hope
Sergei R
Asked: 2020-02-28 03:55:47 +0000 UTC

如何遍历从数据库接收到的数组并更改其中一个字段

  • 0

我从数据库中收到所有列表。

#<ActiveRecord::Relation [#<Item id: 1, name: "AAA", unit_price: 10000><#Item ....]

接下来,我需要通过循环或迭代器将 unit_price 值除以 100,将结果写回并显示在视图中。

我这样尝试:

def index
    @items = Item.all
    @items.each{
        @items[unit_price] = @items[unit_price] /100
    }
end

作为回应,我得到:

未定义的局部变量或方法“unit_price”

我查看哈希手册

user = {name:"Vasya", last_name: "Petrov", age: 20}
user[:name] #=> "Vasya"

我这样尝试:

def index
    @items = Item.all
    @items.each{
        @items[:unit_price] = @items[:unit_price] /100
    }
end

我得到一个答案

没有将 Symbol 隐式转换为 Integer

可能 @items[:unit_price] 值不算整数,虽然它在数据库中是这样,好吧......

    def index
    @items = Item.all
    @items.each{
        @items[:unit_price] = @items[:unit_price].to_i /100
    }
end

我得到一个答案

没有将 Symbol 隐式转换为 Integer

所以@items.unit_price也试过了,没有unit_price这个方法

如何遍历这些数组以及如何访问所需的字段?

ruby-on-rails
  • 2 个回答
  • 10 Views
Martin Hope
Sergei R
Asked: 2020-02-26 05:04:43 +0000 UTC

引导程序形式的验证错误消息

  • 0

我正在使用标准的引导程序表单,验证字段并显示一条错误消息。目前是这样实现的:

<% if @stock.errors.any? %>
<div id="error_explanation">
  <h2>
  <%= pluralize(@stock.errors.count, "error") %> prohibited
    this stock from being saved:
  </h2>
  <ul>
    <% @stock.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
    <% end %>
  </ul>
</div>
<% end %>
<br>
<%= form_for :stock, url: stocks_path do |f| %>
....
<% end %>

消息出去但表单开始分散,那些未通过验证的字段被包装在类为 field_with_errors 的 div 标签中

<div class="field_with_errors">
  <label class="col-2 col-form-label" for="stock-name">Name</label> 
</div>

如何解决这个问题,但最好像Bootstrap一样制作验证错误消息

明明可以把bootstrap样式挂在field_with_errors类上,但是我想反着用bootstrap类。

bootstrap
  • 1 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5