我正在使用Redux,如果用户修改了数据,我想在状态中设置一个标志.
首先,我使用服务器中的一些数据为我的商店补充水分:
let serverData = {toggle: true}
const store = configureStore({data: serverData, originalData: serverData})
Run Code Online (Sandbox Code Playgroud)
然后我有一些减速器:
function data(state = {}, action) {
switch (action.type) {
case TOGGLE:
return {
...state,
toggle: !state.toggle
}
default:
return state
}
}
function changed(state = false, action) {
// This doesn't work; we are actually comparing state.changed.originalData and state.changed.data
return isEqual(state.originalData, state.data)
}
const rootReducer = combineReducers({
data,
originalData: (state={}) => state,
changed
})
Run Code Online (Sandbox Code Playgroud)
我想在这里做的是将changed标志设置为true,如果state.data不再等于state.originalData.但是,使用combineReducers,我无法访问我的changedreducer 中的状态的这些部分.
最常用的方法是什么?
我的 PostgreSQL 数据库中有四个表:
Company User(带有外键列company_id) Location(带有外键列company_id) UserLocations(关联表,具有外键列 user_id 和 location_id)本质上:
我想知道数据库是否有办法限制 UserLocations 关联表中的条目,以便引用的用户和位置必须具有相同的 company_id 值。我不希望 A 公司的用户拥有 B 公司的位置。
我可以在我的应用程序层(rails)检查这一点,但如果存在该选项,我有兴趣使其成为硬数据库级约束。
我正在使用 PostgreSQL 9.4。
我有一张桌子workouts。results用户可以为每个创建多个workout,并且一个result有一个score.
给定一个锻炼 ID 列表和两个用户 ID,我想返回每个用户每次锻炼的最佳分数。如果用户没有该锻炼的结果,我想返回填充/空结果。
SELECT "results".*, "workouts".*
FROM "results" LEFT JOIN "workouts" ON "workouts"."id" = "results"."workout_id"
WHERE (
(user_id, workout_id, score) IN
(SELECT user_id, workout_id, MAX(score)
FROM results WHERE user_id IN (1, 2) AND workout_id IN (1, 2, 3)
GROUP BY user_id, workout_id)
)
Run Code Online (Sandbox Code Playgroud)
在此查询中,左连接充当内连接;如果用户没有得到锻炼结果,我不会得到任何填充。无论存在多少结果,此查询都应始终返回六行。
示例数据:
results
user_id | workout_id | score
-----------------------------
1 | 1 | 10
1 | 3 | 10
1 | 3 …Run Code Online (Sandbox Code Playgroud) 调用 时cast_assoc,我想要“查找或创建”样式的行为。在 Ecto 中是否有一种简单的方法可以做到这一点?
作为一个人为的例子,一个user belongs_to最喜欢的color,它是uniqueby color.name。如果我使用已经存在的最喜欢的颜色创建一个新用户,我会收到一个错误 ( name has already been taken)。相反,我想设置user.color_id为预先存在的color记录。Ecto 中是否有内置功能可以执行此操作,还是我必须推出自己的解决方案?
用户变更集:
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:name])
|> cast_assoc(:color)
end
Run Code Online (Sandbox Code Playgroud)
失败测试:
test "create user with pre-existing color" do
Repo.insert!(%Color{name: "red"})
%User{}
|> User.changeset(%{name: "Jim", color: %{name: "red"}})
|> Repo.insert!
end
Run Code Online (Sandbox Code Playgroud) 有没有什么方法可以embeds_many在没有id/primary_key字段的情况下在 Ecto 中使用?
我的数据库依赖于在这个字段上有一个唯一的索引,而 ecto 自动插入键打破了这个要求。
Postgres 9.4
我有一个像这样的 JSONB 值的记录:
{
"attributeA": 1,
"attributeB": "Foo",
"arrayAttribute": [
{"attributeC": 95, "attributeD": 5},
{"attributeC": 105, "attributeD": 5}
]
}
Run Code Online (Sandbox Code Playgroud)
我想写一个查询,它说:
查找其中 attributeA = 1、attributeB = 'Foo' 的任何项目,并且对于 arrayAttribute 数组中的每个元素,attributeC 在某个值 X 的 10 点范围内。因此,如果 X 为 100,则上述记录将匹配(95 和105 与 100 相差 10 分)。
不幸的是,我真的在 JSONB 查询语法上苦苦挣扎。做到这一点的最佳方法是什么?