【问题标题】:How to build an association using ecto and guardian如何使用 ecto 和 Guardian 建立关联
【发布时间】:2016-11-24 18:26:29
【问题描述】:

不知何故,我无法在 Phoenix / Ecto 中使用 Guardian

MeetingController#create

changeset = case Guardian.Plug.authenticated?(conn) do
    true ->
        Guardian.Plug.current_resource(conn) # == existing user
        |> build_assoc(:meetings) # successfully builds a meeting with user_id
        |> Meeting.changeset_with_user(meeting_params) # removes user_id
     _ ->
        Meeting.changeset(%Meeting{}, meeting_params)
end

会议

schema "meetings" do
    field :title, :string
    field :description, :string

    belongs_to :user, User
end

def changeset(model, params \\ %{}) do
    model
    |> cast(params, [:title], [:description])
end

def changeset_with_user(model, params \\ %{}) do
    model
    |> changeset(params)
    |> assoc_constraint(:user)
end

如何插入带有关联usermeeting?调用build_assoc 正确设置user_id,但调用changeset 会再次删除关联。用户能够成功进行身份验证。我在这里错过了什么?

【问题讨论】:

  • 不应该是cast(params, [:title, :description, :user])吗?

标签: elixir phoenix-framework ecto


【解决方案1】:

看到这个commentchangeset不直接包含关联属性,而是通过changeset.data

我们将从 changeset.data 中提取其他字段,包括 user_id

因此,一旦插入关联,就会正确设置。

【讨论】:

    猜你喜欢
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多