FactoryGirl : How to pass the attribute's value in factory to it's association - factory-bot

How can I pass the 'email' attribute value in a :subscriber factory to it's association :authentication
Eg :
factory :subscriber, :class => Subscriber do
sequence(:name) { |n| "test_user_#{n}" }
sequence(:email) { |n| "test_user_#{n}#example.com"}
association :authentication, factory: :authentication, email: email
end
factory :authentication do
sequence(:email) { |n| "test_user_#{n}#example.com"}
password 'pass'
end
Is giving me error
ArgumentError:
Trait not registered: email

I think you need to make your association call dynamic because of the email variable that can change:
authentication {association :authentication, email: email}

Related

Redux Toolkit - do not send request when query param is invalid

I've checked the redux toolkit docs and don't see an example of this typical use case: do not send the request of the query has an invalid param.
For example, a get request to endpoint /categories/{name} requires a name value. If name does not have a value, then the request should not be made.
const baseQuery = fetchBaseQuery({
baseUrl: Constants.PATHWAY_API_URL
});
export const pathwayApi = createApi({
reducerPath: 'pathwayApi',
baseQuery: baseQueryWithReAuth,
endpoints: builder => ({
getSubCategories: builder.query({
// NETWORK REQUEST SHOULD NOT BE MADE IF "name" param is falsy
query: name => `${Constants.PATHWAY_API.CATEGORIES_PATH_NAME}/${name}`,
}),
}),
});
I want to add this type of param validation to all my queries that require a param value or values. What's the recommended approach / pattern for handling this validation at the createApi (or possibly fetchBaseQuery) layer?
Thanks in advance!
You can actually throw an error in your query function.
export const pathwayApi = createApi({
reducerPath: "pathwayApi",
baseQuery: baseQueryWithReAuth,
endpoints: (builder) => ({
getSubCategories: builder.query({
// NETWORK REQUEST SHOULD NOT BE MADE IF "name" param is falsy
query: (name) => {
if (!name) {
throw new Error("Category name is required.");
}
return `${Constants.PATHWAY_API.CATEGORIES_PATH_NAME}/${name}`;
}
})
})
});
When this happens, your hook will have isError: true but no network request will be made. The error property of your hook will be a SerializedError object with properties name, message and stack, which you can use to display the error in your UI.
This is the same type of error object that you get if you have a TypeError somewhere in your code. Note that JavaScript errors will have error.message while API errors (FetchBaseQueryError) will have error.error.
const Category = ({ name }) => {
const { data, error, isError } = useGetSubCategoriesQuery(name);
return (
<div>
<h3>Name: "{name}"</h3>
{isError && (
<div>{error?.error ?? error?.message}</div>
)}
</div>
);
};
CodeSandbox Link

Strapi - Update Additional Fields on User Model

Problem Statement: Able to register user but unable to update customFields on same model in single request. Detail explanation below.
I have added additional fields to UserModel on Strapi. UserModel Attached
I am building a front end using Nuxt, where admin user can create new users who can access the website. This is not Regular Signup, This is User getting created by admin of the site. I guess even a regular signup I would face this issue.
Admin has all the rights to crud users.
When I submit the form I am getting Forbidden error. Form Attached
Below is my code which handled the submit. I first register the user and based on the user id I try to update First Name and Last name.
handleSubmit() {
if (this.$refs.form.validate()) {
this.loading = true
// console.log(this.username, this.email, this.password)
strapi
.register(this.username, this.email, this.password)
.then(response => {
console.log(response)
strapi
.updateEntry('users', response.user.id, {
firstName: this.firstname,
lastname: this.lastname
})
.then(response => {
this.loading = false
this.$router.push('/users')
})
.catch(err => {
this.loading = false
// alert(err.message || 'An error occurred.')
this.errorMessage = true
this.errorMessageContent = err.message || 'An error occurred.'
})
})
.catch(err => {
this.loading = false
// alert(err.message || 'An error occurred.')
this.errorMessage = true
this.errorMessageContent = err.message || 'An error occurred.'
})
}
}
Below is the console message.
Do you want to update the additional user fields (using PUT method) or passing them to the back-end in the register process (using POST method) ?
If you want to update them, you have to do the following:
Adding fields to you user model (already done)
Make the /update endpoint available in the users-permissions configuration.
See screenshot:
Now you are able to use the PUT method on the endpoint users/:id, which you could do e.g. like this:

How to pass object as JSON to a POST or PUT request in grails

I am using restful service in grails. I have 2 classes Person
import grails.rest.Resource
#Resource(formats=['json', 'xml'])
class Person {
String name
Address address
static constraints = {
}
}
and Address as
import grails.rest.Resource
#Resource(formats=['json', 'xml'])
class Address {
String house
static constraints = {
}
}
and in bootstrap I could create new person entry as follows
new Person(name:"John" , address: new Address(house:"John Villa").save()).save();
but the problem is I want to do the same thing using a POST request with JSON data.
I set the UrlMappings.Groovy like
"/app/person"(resources: "person", includes: ['index', 'show', 'save', 'update', 'delete', 'create', 'patch'])
"/app/address"(resources: "address", includes: ['index', 'show', 'save', 'update', 'delete', 'create', 'patch'])
then I tried using POSTMAN rest client by sending a POST request to '/app/person' with JSON data
{
"name":"john" ,
"address": "{'house' :'sample address' }"
}
but it gives error 422 unprocessable entity.
How can I do the same using JSON ? I want to do both insertion and updation using POST and PUT methods.
The issue is with the JSON you are sending. While it's valid JSON it's not the correct representation for your resource. Your JSON should be:
{
"name":"john",
"address":
{
"house":"sample address"
}
}
As you can see from the above that the address property is actually a nested object and not a String like you are sending.
Moreover did you check guides on http://grails.github.io/grails-doc/latest/guide/webServices.html ?
Especially I would like you to check section:
grails.mime.types = [
…
json: ['application/json', 'text/json'],
…
xml: ['text/xml', 'application/xml']
]
Remember that when you process '/app/person' with PersonInstance, you in fact execute '/app/person/index/' with PersonInstance (so debug it's source if needed).
Also double check 'id' column in your classes.

Mongoid add field but don't exist in mongodb

I use Mongoid to query db in a rails project.
When i add a field "scope" to a User Model
class User
include Mongoid::Document
field :scope, type: String
end
When use rails console, we can find this field have add to User model.
But when we go to mongodb console to view users data, use db.users.find(), it don't have scope field yet.
also when i want update scope field in rails console. It always have below error.
pry(main)> user = User.first
=> #<User _id: 521dcd4464fad29a74000009, scope: "private", xxx_id: "521dcd4464fad29a74000008">
pry(main)> user.update_attributes(scope: "public")
Moped::Errors::OperationFailure: The operation: #<Moped::Protocol::Command
#length=84
#request_id=17
#response_to=0
#op_code=2004
#flags=[]
#full_collection_name="blog_development.$cmd"
#skip=0
#limit=-1
#selector={:getlasterror=>1, :safe=>true}
#fields=nil>
failed with error 11000: "E11000 duplicate key error index: blog_development.users.$_id_ dup key: { : ObjectId('521dcd4464fad29a74000009') }"
Any one can tell me why?
Just adding field :scope, type: String to your model won't add it to the underlying MongoDB collection, that just tells Mongoid that it should allow the model to have a scope for accessors, mutators, validations, mass-assignment, ... Keep in mind that different documents in a MongoDB collection can have entirely different properties so the schema is really a fiction that is applied by Mongoid.
If you want all your users to have a scope then you'd have to say something like this:
User.collection.find().update_all(:$set => { :scope => 'whatever it should be' })
to manually add it to all the documents.
The field exists in your saved objects. But to be able to find one with your asked value, you have to create one.
class User
include Mongoid::Document
field :name, type: String
field :age, type: Integer
end
User.find(name: 'John')
# => nil
User.create({ name: 'John', age: '18' })
# => User 284692 :name => 'John', :age => 18
User.find(name: 'John')
# => User 284692 :name => 'John', :age => 18
Hope it helps.
edit after 'mu is too short' post :
To fill all existing objects in db, just provide a :default value to your field
class User
field :name, type: String, default: 'Martin Dupont'
end
Thanks for reply.
The reason is in this model, i have overwrite new_record? method. So cause this error.

Rspec is not working properly with mongodb

I have the following user class
class User
include MongoMapper::Document
key :email, String, :unique => true
end
and my rspec code
before do
#user = FactoryGirl.create(:user)
end
describe "when email address is already taken" do
before do
user_with_same_email = #user.dup
user_with_same_email.email = #user.email
user_with_same_email.save
end
it { should_not be_valid }
end
raises the following error
1) User when email address is already taken
Failure/Error: it { should_not be_valid }
expected #<User _id: BSON::ObjectId('5236bec5ebe8660fcb00001a'), accepted_tender_ids: [], avatar: #<Avatar _id: BSON::ObjectId('5236bec3ebe8660fcb000001'), digest: "c7358a60a79905a7d4e3383ba905f1baaab278b06a6f751971344cb91763068f", image: "c7358a60a79905a7d4e3383ba905f1baaab278b06a6f751971344cb91763068f">, busy: false, completed_count: 0, completed_tender_ids: [], confirmed: true, dialogs: [], dislikes: 0, email: "maurice_langworth#treutel.com", role: "customer", subspecializations: [], type: "personal"> not to be valid
Expected user is not valid but it is valid
user_with_same_email will fail to save, so there will not be a second user in the database with your email; assuming that subject is #user, there will be no conflict and the user will be valid.
Did you forget to define subject as user_with_same_email?