Ecto association custom name - associations

Is it possible to set a custom name to an association?
For example: I have classical "User -> Posts" situation:
create table(:users) do
add :first_name, :string
add :last_name, :string
timestamps()
end
create table(:posts) do
add :text, :string
add :user_id, references(:users, on_delete: :nothing)
timestamps()
end
and schema:
schema "users" do
field :first_name, :string
field :last_name, :string
has_many :posts, MyProj.Post
timestamps()
end
schema "posts" do
field :text, :string
belongs_to :user, MyProj.User
timestamps()
end
I want the association in posts to be called not user but author.
If I change my schema to:
schema "posts" do
field :text, :string
belongs_to :author, MyProj.User, [foreign_key: :user_id]
timestamps()
end
I get error: field 'author' in 'select' does not exist in schema MyProj.Post
Edited:
I get the error trying to query all posts:
def all_posts _root, _args, _info do
posts_query = from p in Post,
preload: [:author],
select: %{
posted_by: p.author,
text: p.text
}
posts = Repo.all(posts_query)
{:ok, posts}
end
Stack-trace:
[info] Sent 500 in 30ms
[error] #PID<0.478.0> running MyProj.Endpoint terminated
Server: localhost:4000 (http)
Request: POST /graphiql
** (exit) an exception was raised:
** (Ecto.QueryError) lib/my-proj/resolvers/post_resolver.ex:7: field `author` in `select` does not exist in schema MyProj.Post in query:
from p in MyProj.Post,
select: %{posted_by: p.author, text: p.text},
preload: [:author]
(ecto) lib/ecto/repo/queryable.ex:124: Ecto.Repo.Queryable.execute/5
(ecto) lib/ecto/repo/queryable.ex:37: Ecto.Repo.Queryable.all/4
(my-proj) lib/my-proj/resolvers/post_resolver.ex:17: MyProj.PostResolver.all_posts/3
(absinthe) lib/absinthe/resolution.ex:147: Absinthe.Resolution.call/2
(absinthe) lib/absinthe/phase/document/execution/resolution.ex:191: Absinthe.Phase.Document.Execution.Resolution.reduce_resolution/1
(absinthe) lib/absinthe/phase/document/execution/resolution.ex:161: Absinthe.Phase.Document.Execution.Resolution.do_resolve_field/4
(absinthe) lib/absinthe/phase/document/execution/resolution.ex:147: Absinthe.Phase.Document.Execution.Resolution.do_resolve_fields/6
(absinthe) lib/absinthe/phase/document/execution/resolution.ex:87: Absinthe.Phase.Document.Execution.Resolution.walk_result/5
(absinthe) lib/absinthe/phase/document/execution/resolution.ex:57: Absinthe.Phase.Document.Execution.Resolution.perform_resolution/3
(absinthe) lib/absinthe/phase/document/execution/resolution.ex:25: Absinthe.Phase.Document.Execution.Resolution.resolve_current/3
(absinthe) lib/absinthe/pipeline.ex:247: Absinthe.Pipeline.run_phase/3

The problem not in the association's name but in my misunderstanding how does Ecto interpret queries.
Since entities in queries are rather "DB table" rows then schema struct entities, in
select: %{
posted_by: p.author,
text: p.text
}
Ecto is trying to find a table column called host, which doesn't exists.
In order to "fix" this query I needed to think about it in more "SQL-ish" way:
posts_query = from p in Post,
join: author in assoc(p, :author),
select: %{
posted_by: author,
text: p.text
}

Related

I get "unknown attribute 'password' for User." error while runing User.create on rails consol

I am trying to create User using
User.create ({email:"ayzabc66#gmail.com", password:"password",password_confirmation:"password"})
but I keep on getting below error:
/.rvm/gems/ruby-3.0.0/gems/activemodel-7.0.3/lib/active_model/attribute_assignment.rb:51:in `_assign_attribute': unknown attribute 'password' for User. (ActiveModel::UnknownAttributeError)
I have already uncommented gem "bcrypt", "~> 3.1.7" and ran bundle.
This is what my user.rb looks like:
class User < ApplicationRecord
#email :string
#password_digest:string
#password:string
#password_confirmation:string virtual
has_secure_password
end
And my db>migrate looks like:
class CreateUsers < ActiveRecord::Migration[7.0]
def change
create_table :users do |t|
t.string :email
t.string :password_digest
t.timestamps
end
end
end
If you run the following in Rails Console, do you get the list of attributes that you would expect?
=> User
If so, I would try uncommenting the lines that you have in your User model and see if that helps, so it would look like this:
class User < ApplicationRecord
email :string
password_digest:string
password:string
password_confirmation:string virtual
has_secure_password
end

Structural error property type should be equal to one of the allowed values allowedValues: string, number, boolean, integer, array in Swagger editor

I'm using springfox 2.9.2 and want test my swagger JSON as YAML in https://editor.swagger.io/
I have property with #ApiParam annotation type: object
#ApiParam(value = "metadata file")
protected Object metadataFile;
but when I test my generated json on swagger editor I got this error:
Structural error at ---.parameters.5.type should be equal to one of
the allowed values allowedValues: string, number, boolean, integer,
array Jump to line ---
there is way to allowed property type object in this section?
the section that trigger the problem
paths:
:
post:
parameters:
name: metadataFile
in: query
description: ...
required: false
type: object
Swagger documentation (go to the bottom of the page): https://swagger.io/docs/specification/2-0/describing-parameters/
"Can I have an object as a query parameter?
This is possible in OpenAPI 3.0, but not in 2.0."

Error while editing existing GSI on my scheme

I am using AppSync with DynamoDB and GraphQL API. My current scheme works as expected but when trying to edit existing GSI I am getting an error.
My current scheme looks like this:
type Item #model
#key(fields: ["id", "version"])
#key(name: "type-subtype", fields: ["type", "subtype"])
{
id: ID!
version: String!
type: String!
subtype: String!
}
I want to change GSI defined here to be:
#key(name: "version-type-subtype", fields: ["version", "type", "subtype"]
The error I am getting is Schema Creation Status is FAILED with details: Failed to parse schema document - ensure it's a valid SDL-formatted document.
Can someone help? Is there any constraint using sort key from primary index as hash in GSI that I am not aware of?
Thanks

Gedmo Translatable yaml mapping

Is it possible to map Gedmo with yaml ? I'm using yaml file in my project and I would like to use Translatable from doctrine extensions but I have a problem with it.
I have something like that (one entity / one translation table) :
class CategoryTranslation extends \Gedmo\Translatable\Entity\MappedSuperclass\AbstractTranslation
{
/**
* All required columns are mapped through inherited superclass
*/
}
but, when I run "doctrine:schema:update --dump-sql" command, I've got an error :
There is no column with name 'locale' on table 'category_translation'.
I have the feeling that yaml mapping "can't see" Gedmo AbstractTranslation class...
Do you have an idea of the problem ?
Thank you !
EDIT :
To avoid discussions in comments, I post an answer.
MyProject\MyBundle\Entity\Category:
type: entity
table: category
repositoryClass: MyProject\MyBundle\Repository\CategoryRepository
gedmo:
tree:
type: nested
translation:
locale: locale
entity: MyProject\MyBundle\Entity\Translation\CategoryTranslation
fields:
label:
type: string
length: 255
gedmo:
- translatable
With this config, I had to create a Translation.CategoryTranslation.orm.yml file because there is no database migration. And, there problem is really here :
MyProject\MyBundle\Entity\Translation\CategoryTranslation:
type: entity
table: category_translation
repositoryClass: Gedmo\Translatable\Entity\Repository\TranslationRepository
indexes:
category_translation_idx:
columns: [ locale, object_class, field, foreign_key ]
id:
id:
type: integer
generator:
strategy: AUTO
fields:
locale:
type: string
length: 8
object_class:
type: string
length: 255
field:
type: string
length: 32
foreign_key:
type: string
length: 64
content:
type: text
By doing this, the database migration works. I have a new table named category_translation. But, when I try to add a new translation, there is an error in my sql request generated by doctrine. Object_class field and foreign_key are null.
Here, the SQL request generated by doctrine :
INSERT INTO category_translation (locale, object_class, field, foreign_key, content) VALUES (?, ?, ?, ?, ?)' with params [\"fr\", null, \"name\", null, \"toto\"]:\n\nSQLSTATE[23000]: Integrity constraint violation: 1048 Column 'object_class' cannot be null"}

Model passes validation of :presence => true and still nil in database

user_type is a column in user model and it has to be :presence => true. It rejects in rspec when passing a nil to user_type. However the factory_girl can store a nil user_type into the field with sqlite3.
Running rails 3.1.0. rspec 2.6.0 and factory_girl 2.1.0
//user model:
validates :user_type, :presence => true
//Factory girl definition:
Factory.define :user do |user|
user.name "Test User"
user.email "test#test.com"
user.password "password1"
user.password_confirmation "password1"
user.status "active"
user.user_type "employee"
end
Factory.define :user_level do |level|
level.role "sales"
level.position "member"
level.team 1
level.association :user
end
//rspec case: passed
it "should reject user type nil" do
user = Factory.build(:user, :user_type => nil)
user.should_not be_valid
end
it "should take user type 'employee'" do
user = Factory.build(:user, :user_type => 'employee')
user.errors[:user_type].should be_empty
user.should be_valid
end
Any thoughts? thanks.
As Michael Hartl pointed out in his excellent Rails tutorial, Factory Girl bypasses attr_accessible in the model. For instance, you can overwrite the "magic" columns using Factory Girl. Perhaps this applies to validations as well?
It seems like it would be better in this case to actually create your user with User.new, since you are testing the process of creation and validation itself.

Resources