Screencast
27. AirBnB Clone LiveView part 2
seed
stream
In this video, we're continuing our Airbnb clone with Phoenix LiveView. Last time, we set up a fresh Phoenix app and replaced the default welcome page with our custom layout. Now, we'll add real content by creating a database table for apartment listings—the foundation for showing actual rentals on our site. I'll guide you through loading seed data so our homepage displays genuine properties with real details like locations, prices, and amenities.
Implementing Database Constraints for Data Integrity
When building a property rental platform with Phoenix, it's crucial to ensure data integrity. For our Airbnb clone, we need to guarantee that apartment prices are always positive. I'll show you how to implement this using database constraints in both the migration and schema files.
# In your migration file
defmodule MyBnB.Repo.Migrations.CreateRooms do
use Ecto.Migration
def change do
create table(:rooms) do
# Other fields...
add :amount, :integer
# ...
timestamps(type: :utc_datetime)
end
# Database-level constraint ensuring positive amounts
create constraint(:rooms, :amount_must_be_positive, check: "amount > 0")
end
end
# In your schema file
defmodule MyBnB.Apartments.Apartment do
use Ecto.Schema
import Ecto.Changeset
schema "apartments" do
# Other fields...
field :amount, :integer
# ...
end
def changeset(room, attrs) do
room
|> cast(attrs, [:name, :headline, :description, :address, :zip, :city, :state, :amount, :currency])
|> validate_required([:name])
# Reference the constraint in your changeset
|> check_constraint(:amount, name: :amount_must_be_positive)
end
end
What You Will Learn:
- How to implement database constraints for data integrity
- Referencing database constraints in Ecto changesets for proper validation
- Creating a Phoenix context to organize your apartment-related functionality
- Seeding your database with realistic property data
- Using LiveView streams for efficient rendering of property listings
- Implementing currency formatting for proper price display