Find the Movie With Maximum Reviews Ruby on Rails

In the previous article, we've added user hallmark and authorization with devise, and nosotros've set the Movies model.

In this article, we'll add the CRUD functionality - create, read, update, delete - for the Movies model.

Build a simple movie review website in Rails 6 Image past CodingExercises

Let'due south begin by inspecting our database tables using the Rails console:

              track c ActiveRecord::Base of operations.connection.tables                          

The returned output:

              => ["schema_migrations", "ar_internal_metadata", "users", "movies"]                          

Alright, let's inspect the columns in the movies tabular array.

              Movie.columns.map(&:proper name)                          

Here's the output:

              => ["id","title","description","img","comprehend","rate","user_id","created_at","updated_at"]                          

Let's load all the movies; note: we know this will not return annihilation:

As expected the above ActiveRecord query will map onto an PostgreSQL query, and execute it, returning empty:

              Picture Load (0.5ms) SELECT "movies".* FROM "movies" LIMIT $i [["LIMIT", 11]] => #<ActiveRecord::Relation []>                          

Dandy, everything in our model seems to work.

Before nosotros can effectively work with the Moving picture Model, we need to add the movie controller too.

Adding Motion picture Controller

To add together the pic controller, nosotros'll run this on the control line:

              rails chiliad controller Movies index show new create edit update destroy                          

Like to how we added a unmarried habitation activeness to the Pages controller, nosotros've added all the needed actions for the Movies controller. Generating the movie controller from the command line

To see the change to our file structure, let's run git status: Running git status after generating the movie controller

The newest updates are committed as "Add the Movies controller" commit message.

Permit'southward also do a git diff --stat to compare the newest commit with the previous i. To know the actual SHAs that we'll be comparing, nosotros'll do the git log --oneline first, then take the ii nigh recent ones.

              git unequal 30dd5c9 5ab103a --stat                          

Here'southward a screenshot of the output: Running git diff --stat after committing movie controller changes

Currently the movies_controller.rb looks like this:

                              class                MoviesController                <                ApplicationController                def                index                end                def                testify                end                def                new                end                def                create                cease                def                edit                end                def                update                finish                def                destroy                end                terminate                          

Let'due south update it to this:

                              before_action                :set_movie                ,                only:                                [                :show                ,                :edit                ,                :update                ,                :destroy                ]                def                index                @movies                =                Motion picture                .                all                terminate                def                show                end                def                new                @flick                =                Movie                .                new                puts                @movie                end                def                create                @user                =                current_user                puts                @user                @film                =                @user                .                movies                .                create                (                params_requre                )                redirect_to                movies_path                #@motion picture = @user.movies.new(params_requre)                # if movie.save                end                def                edit                stop                def                update                puts                "77777777777777777777"                @movie                .                update                (                params_requre                )                redirect_to                movies_path                end                def                destroy                finish                def                set_movie                @picture show                =                Movie                .                find                (                params                [                :id                ])                puts                @movie                terminate                protected                def                params_requre                params                .                require                (                :movie                ).                allow                (                :title                ,                :description                )                terminate                finish                          

Additionally, looking at the Movie model (divers in the models/pic.rb file) nosotros can run into that information technology defines the relationship between users and movies:

                              form                Movie                <                ApplicationRecord                belongs_to                :user                end                          

We besides need to define the other side of the human relationship, inside the models/user.rb file, past calculation this line just above the endmost terminate line of the User form definition.

Now the entire updated models/user.rb files looks like this:

                              form                User                <                ApplicationRecord                # Include default devise modules. Others available are:                # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable                devise                :database_authenticatable                ,                :registerable                ,                :recoverable                ,                :rememberable                ,                :validatable                has_many                :movies                cease                          

Let'south add the changes to movies controller and user model, in a commit titled "Update user model and movies controller".

Now that we've got everything fix, let'due south accept a quick detour and add a new movie using the rails console.

Why?

Because information technology'due south faster to do it this manner than having to add the code to all the views that we've added when the movies controller was generated. Currently, all these view files are only empty slots waiting to exist filled with actual code. Right now, they're but static HTML, like, for example, the views/movies/create.html.erb file:

                              <h1>Movies#create</h1>                <p>Find me in app/views/movies/create.html.erb</p>                          

Let'due south also come across how the generated movies controller affected the contents of the routes.rb file:

                              Rails                .                application                .                routes                .                draw                do                go                'movies/index'                get                'movies/show'                get                'movies/new'                go                'movies/create'                get                'movies/edit'                get                'movies/update'                go                'movies/destroy'                root                'pages#home'                devise_for                :users                #get 'pages/home'                # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html                terminate                          

We'll go rid of all these get requests and instead merely practise resources, similar this:

                              Track                .                awarding                .                routes                .                draw                do                # get 'movies/alphabetize'                # get 'movies/show'                # get 'movies/new'                # go 'movies/create'                # get 'movies/edit'                # get 'movies/update'                # become 'movies/destroy'                root                'pages#habitation'                resources                :movies                devise_for                :users                # For details on the DSL available within this file, run into https://guides.rubyonrails.org/routing.html                end                          

Alright, so let's accept our detour and apply the rails panel first.

Add together a New Film With Track Panel

To add together a movie, we commencement need to make sure we take a user in the database. Permit'due south run User.outset and User.second in the panel.

Running User.first and User.second in rails console

As we tin see, we have the first User in the database, but for the second, it returns nil.

Let'due south at present see if at that place are any movies that vest to User.starting time:

Checking to see if there are any movies that belong to the first user

Finally, let's add together ane.

We'll need to add all the entries for each of the movies table columns, except for the first table column, id.

Equally a reminder, hither'southward what gets returned from running Moving-picture show.columns.map(&:name)

              => ["id","title","description","img","encompass","charge per unit","user_id","created_at","updated_at"]                          

Ok, so at present we're ready to add a movie.

I've split the following code on several lines for easier reading; still, you should type information technology equally a one-liner in the Rails console:

                              User                .                get-go                .                movies                .                new                (                championship                :"The Matrix"                ,                description                :"Neo Anderson lives in a simulation..."                ,                img                :"https://upload.wikimedia.org/wikipedia/en/thumb/c/c1/The_Matrix_Poster.jpg/220px-The_Matrix_Poster.jpg"                ,                cover                :"https://upload.wikimedia.org/wikipedia/en/pollex/c/c1/The_Matrix_Poster.jpg/220px-The_Matrix_Poster.jpg"                ).                save                          

Here'south the output in the console: The result of adding a new movie to a user using active record

Let'southward now run User.offset.movies over again:

Here's the output this fourth dimension: Running User first movies again

Now that we have added our showtime movie using the Rail console, let's add the views so that our web app visitors can also do it from our web app's frontend.

Calculation the Movie CRUD Views

Let's kickoff with movies edit. Open app/views/movies/edit.html.erb and add together this code at the bottom:

                              <%=                form_form                :movie                ,                url:                                movie_path                ,                method                :patch                practice                |                f                |                %>                Title:                <%=                f                .                text_field                :title                %>                <br>                Description:                <%=                f                .                text_field                :description                %>                <br>                <%=                f                .                submit                %>                <%                end                %>                          

Now, visit this URL: localhost:3000/movies/edit.

Y'all'll get an error.

Why is that?

To sympathize why this is happenning, permit'due south visit a different URL: localhost:3000/movies/new.

This time, the actual URL gets served without issues: The movies new url is served in the browser

The reason is the lawmaking in the movies_controller.rb.

While we practise accept the lawmaking for calculation a new flick in the controller, nosotros don't have a definition for the edit action:

                              def                new                @picture show                =                Movie                .                new                puts                @pic                end                .                .                def                edit                end                          

Note the the two vertical dots in the lawmaking above are added for brevity, and are a stand-in for the actual code.

Manifestly, we need to add together some code to our edit activeness.

Here it is:

                              def                edit                @movie                =                Movie                .                detect                (                params                [                :id                ])                stop                          

To be continued…

kaplanemeart.blogspot.com

Source: https://www.codingexercises.com/projects/build-a-simple-movie-review-website-in-rails-6-part-3

0 Response to "Find the Movie With Maximum Reviews Ruby on Rails"

Enviar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel