Again, because the user is simply passing a string, we don’t have the ID information at hand. However here we expect tags to be sent in a string separated by comma.įurthermore cast_assoc/3 relies on the primary key field for each tag sent in order to decide if it should be inserted, updated or deleted. To do so correctly, Ecto requires tags to be sent as a list of maps. Remember the cast_assoc/3 changeset function was designed to receive external parameters and compare them with the associated data in our structs. While the constraints above sound reasonable, that’s exactly what put us in trouble with cast_assoc/3. Once this data is received in the server, we will break it apart into multiple tags and associate them to the post, creating any tag that does not yet exist in the database. Now let’s also imagine we want the user input such tags as a list of words split by comma, such as: “elixir, erlang, ecto”. It is important to add an index at the database level instead of using a validation since there is always a chance two tags with the same name would be validated and inserted simultaneously, passing the validation and leading to duplicated entries. Note we added a unique index to the tag name because we don’t want to have duplicated tags in our database. Our migrations would look like: create table(:posts) doĬreate table(:posts_tags, primary_key: false) do ![]() This is a classic scenario where we would use many_to_many associations. Not only that, a given tag may also belong to many posts. Imagine we are building an application that has blog posts and such posts may have many tags. We will also peek at the upsert features coming in Ecto 2.1. ![]() In this chapter we are going to look at _assoc/4 in contrast to cast_assoc/3 and explore some examples. While in the previous chapter we were able to follow the rules imposed by cast_assoc/3, doing so is not always possible nor desired. In the previous chapter we have learned about many_to_many associations and how to map external data to associated entries with the help of _assoc/3. Reserve Download your copy now if you want to receive the next beta and be notified of future versions. Note: This is a sample chapter of the upcoming beta version of our “What’s new in Ecto 2.0” free book.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |