I want to restrict users from having more than 1 job Application for a particular job.
Here are my routes:
resources :jobs do
resources :job_applications
end
job.rb
class Job < ApplicationRecord
has_many :job_applications
validate :limit_user_to_one_job_application
private
def limit_user_to_one_job_application
if user.job_applicaitons.count > 1
self.errors.add(:base, "You can only have one job application")
end
end
end
job_application.rb
class JobApplication < ApplicationRecord
belongs_to :user
belongs_to :job
end
user.rb
class User < ApplicationRecord
has_one :job_application
end
job_application_controller.rb
class JobApplicationsController < ApplicationController
before_action :authenticate_user!
def new
#job = Job.find(params[:job_id])
#job_application = #job.job_applications.create
end
def create
#job = Job.find(params[:job_id])
#job_application =
#job.job_applications.create(job_application_params)
#job_application.user_id = current_user.id
#job_application.save
end
in my new.html.erb file to create new job application
<%= form_with(model: [ #job, #job.job_applications.build ],local: true) do |f| %>
<%= job_application attributes %> <br>
<%= job_application attributes %> <br>
..........
<%= f.submit %>
The above code works, the user is enable to create many job applications for a particular job but only the first job in saved in his database. So ,I want the user to be restricted to create only one job application for a particular job
As per the description mentioned in the post you can manage with uniqueness validation in join model.
class JobApplication < ApplicationRecord
belongs_to :user
belongs_to :job
validates_uniqueness_of :user_id, scope: :job_id
end
This validation will prevent creation of duplicate record in the join model based on the pair for user_id and job_id.
Hope this helps.
You can do this on the controller or the model.
before_action :find_job, except: [:index, :new, :create]
before_action :limit_user_to_one_job_application, only: [:new, :create]
...
private
def find_job
#job = Job.find(params[:job_id])
end
def limit_user_to_one_job_application
if #job.job_applications.where(:user => current_user).count == 1
return redirect_to jobs_path, :notice => "You can only have one job application"
end
end
You'll find that it may be better to make #job.job_applications.where(:user => current_user).count == 1 a method on User, but for simplicity sake I was explicit in its intent.
Or the model (something like):
class JobApplication < ApplicationRecord
validate :limit_user_to_one_job_application
private
def limit_user_to_one_job_application
if user.job_applicaitons.count > 1
self.errors.add(:base, "You can only have one job application")
end
end
end
Related
I'm making simple CRUD and the current goal is to add data. However, I found that I can't add any data, and the terminal log also shows "[Webpacker] Everything's up-to-date. Nothing to do", which means there is no error message.
According to my design in the controller, the new data must have failed, so I stopped at new.html.erb. I'm guessing it has something to do with the model's relationship.
This is model User
class User < ApplicationRecord
has_many :reviews
has_many :recipes, through: :reviews
end
This is the model Recipe
class Recipe < ApplicationRecord
has_many :reviews
belongs_to :user
end
This is model Review
class Review < ApplicationRecord
belongs_to :user
belongs_to :recipe
end
This is the RecipeController
class RecipesController < ApplicationController
def index
#recipes = Recipe.all
end
def new
#recipe = Recipe.new
end
def create
#recipe = Recipe.new(recipe_params)
if #recipe.save
redirect_to recipes_path, notice: "Successful!"
else
render :new
end
end
private
def recipe_params
params.require(:recipe).permit(:title, :money)
end
end
this is the web page
<h1>Add New One</h1>
<%= form_for(#recipe) do |r| %>
<%= r.label :title, "Title" %>
<%= r.text_field :title%>
<%= r.label :money, "Budget" %>
<%= r.text_field :money %>
<%= r.submit %>
<% end %>
<%= link_to "Back to list", recipes_path %>
You should first add a callback to ensure that only signed in users can create recipes (unless you actually want to let anomynous users create/update/delete recipies).
For example with Devise you would use its authenticate_user! helper which will bail and redirect to the sign in path if the user is not authenticated:
class RecipesController < ApplicationController
before_action :authenticate_user!, only: [:new, :create]
# ...
end
If you're reinventing the authentication wheel you should create a similiar method which is used to prevent access.
You would then initialize the resource off the current user:
class RecipesController < ApplicationController
before_action :authenticate_user!, except: [:show, :index]
def create
#recipe = current_user.recipes.new(recipe_params)
if #recipe.save
redirect_to recipes_path, notice: "Successful!"
else
render :new
end
end
end
Here I am assuming that you have a current_user method which will retrieve the user based on an id stored the session.
Since you have an indirect assocation this will create a row in the reviews table with the users id and the recipe id as the record in the recipies table.
You also want to display the validation errors in the form so that the user gets feedback.
You are probably right that it is a validation error related to the belongs_to relationship. You should display validation errors for your form as described here https://guides.rubyonrails.org/getting_started.html#validations-and-displaying-error-messages
I am attempting to develop a model in which a user can add the recipe they are viewing to an existing menu of recipes they have created, similar to adding a song to a custom playlist. I believe I have the models set up correctly (using a many to many through relationship) however I am unsure how to go about the adding of the actual records to a selected collection. Any guidance would be helpful. My code is as below.
Menus Controller
class MenusController < ApplicationController
before_action :set_search
def show
#menu = Menu.find(params[:id])
end
def new
#menu = Menu.new
end
def edit
#menu = Menu.find(params[:id])
end
def create
#menu = current_user.menus.new(menu_params)
if #menu.save
redirect_to #menu
else
render 'new'
end
end
def update
#menu = Menu.find(params[:id])
if #menu.update(menu_params)
redirect_to #menu
else
render 'edit'
end
end
def destroy
#menu = Menu.find(params[:id])
#menu.destroy
redirect_to recipes_path
end
private
def menu_params
params.require(:menu).permit(:title)
end
end
Menu Model
class Menu < ApplicationRecord
belongs_to :user
has_many :menu_recipes
has_many :recipes, through: :menu_recipes
end
menu_recipe Model
class MenuRecipe < ApplicationRecord
belongs_to :menu
belongs_to :recipe
end
Recipe Model
class Recipe < ApplicationRecord
belongs_to :user
has_one_attached :cover
has_many :menu_recipes
has_many :menus, through: :menu_recipes
end
User Model
class User < ApplicationRecord
has_secure_password
has_one_attached :profile_image
has_many :recipes
has_many :menus
end
You can do something like :
def add_recipe_to_menu
menu = current_user.menus.find params[:id]
recipe = current_user.recipes.find params[:recipe_id]
menu.recipes << recipe
end
It will add a viewing recipe to existing menu of recipes.
First make sure you build the new record off the user:
class MenusController < ApplicationController
# make sure you authenticate the user first
before_action :authenticate_user!, except: [:show, :index]
def new
#menu = current_user.menus.new
end
def create
#menu = current_user.menus.new(menu_attributes)
# ...
end
end
Then we can just add a select to the form where the user can select from his recipes:
# use form_with in Rails 5.1+
<%= form_for(#menu) do |f| %>
... other fields
<div class="field">
<%= f.label :recipe_ids %>
<%= f.collection_select :recipe_ids, f.object.user.recipies, :id, :name, multiple: true %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
f.object accesses the model instance wrapped by the form builder.
recipe_ids is a special setter/getter created by ActiveRecord for has_many associations. As you may have guesses it returns an array of ids and lets the association be set with an array of ids - automatically inserting/deleting rows in the join table in the process.
You then just need to whitelist the recipe_ids param:
def menu_attributes
params.require(:menu)
.permit(:foo, :bar, recipe_ids: [])
end
recipe_ids: [] whitelists an array of permitted scalar types. Since this is a hash option it must be listed after any positional arguments to be syntactically valid.
rb(main):003:0> params.require(:menu).permit(:foo, recipe_ids: [], :bar)
SyntaxError: (irb):3: syntax error, unexpected ')', expecting =>
I'm building a job board application. I'm new to programming and am teaching myself the rails framework.
I'm using Devise for authentication. I will have two different types of users; Job Seeker and Employer. The job seeker will create a profile and search for job postings and the employer will create a company profile and post job listings. In the future, the employer will also be able to search for employees based on qualifications, experience, education, etc. but for now I'm just building my MVP.
This type of functionality is tricky, namely because you have to put functionality before implementation (IE most people get hung up about Devise, whereas it might not feature at all)
You have two ways:
Roles (authorization)
Multiple models (authentication)
Devise is an authentication system (user logged in); you may be better using authorization (can user do x or y). Authorization is out of Devise's scope.
Whilst you could use multiple models (Devise), I think it creates too much unnecessary bloat for what you need.
Instead, I would use a very simple role system (using enum):
#app/models/user.rb
class User < ActiveRecord::Base
enum role: [:job_seeker, :employer]
has_one :profile
before_create :build_profile
has_many :applications
has_many :listings, through: :applications
end
#app/models/application.rb
class Application < ActiveRecord::Base
belongs_to :listing
belongs_to :user
end
#app/models/listing.rb
class Listing < ActiveRecord::Base
has_many :applications
has_many :applicants, through: :applications, class_name: "User", foreign_key: :user_id
end
You'll need to add a role column (int) to your users table. You'll create the default role by using a default: [x] switch when creating your column:
def change
add_column :users, :role, :integer, default: 0 #-> defaults to job seeker
end
--
You've described several factors which would lend themselves perfectly to this:
Job seeker will create a profile
Employer will create a profile and post listings
... all meaning your "flow" will remain similar for both user types. You'd just have to manage what each user can do with authorization.
Setup
#config/routes.rb
resource :profile, controller: :users, only: [:show, :update] #-> url.com/profile
resources :listings, only: [:show] do
post :apply, on: :member #-> url.com/listings/:id/apply
end
resources :companies, controller: :users, only: [:show]
#app/controllers/users_controller.rb
class UsersController < ApplicationController
#show will automatically be loaded
def update
current_user.update profile_params
end
private
def profile_params
params.require(:user).permit(profile_attributes: [:name, :etc, :etc])
end
end
#app/views/users/show.html.erb
<%= form_for current_user do |f| %>
<%= f.fields_for :profile do |p|
<% if current_user.job_seeker? %>
<%= f.text_field :name, placeholder: "Your name" %>
<% elsif current_user.employer? %>
<%= f.text_field :name, placeholder: "Company name" %>
<% end %>
<% end %>
<%= f.submit %>
<% end %>
You'd then be able to use the following to check whether a user can create listings, or just view:
#app/controllers/listings_controller.rb
class ListingsController < ApplicationController
before_action :check_seeker, only: [:apply]
before_action :check_employer, only: [:new, :create, :destroy]
def new #-> employers
#listing = current_user.listings.new
end
def apply #-> job seekers
#listing = Listing.find params[:id]
#application = current_user.applications.new
#application.listing = #listing
redirect_to #listing, notice: "Application successful!" if #application.save
end
private
def check_seeker
redirect_to listings_path, notice: "Only Job Seekers Allowed" unless current_user.job_seeker?
end
def check_employer
redirect_to root_url, notice: "Only Employers Allowed" unless current_user.employer?
end
end
Hopefully this gives you the gist.
Devise
To get Devise working with your new column, you'll need to extend the Devise Sanitizer:
#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << :role
end
end
This will allow you to change the role field on signup:
#app/views/devise/registrations/new.html.erb
.....
<%= f.select :role, User.roles %>
Devise is good for authentication but for role and access control you may want to look into Rolify: https://github.com/RolifyCommunity/rolify.
This will allow you to keep a single user model and control access to different features with Role queries, ie:
unless current_user.has_role?(:admin)
redirect_to ...
else
render ...
end
For roles you can use CanCanCan gem and RoleModel gem with devise which will be better for user with different roles.
CanCanCan
Defining abilities using cancancan
Role model gem
Example for user roles with above gems..
I have my app setup where users can write reviews for a movie. What I'd like to do is limit the user to create only one review per movie. I've managed to accomplish this in my reviews controller as so:
class ReviewsController < ApplicationController
before_action :has_reviewed, only [:new]
....
def has_reviewed?
if Review.where(user_id: current_user.id, movie_id: #movie.id).any?
redirect_to movie_reviews_path
flash[:notice] = "You've already written a review for this movie."
end
end
end
Where I'm now having trouble is translating this same logic into my index view template with the helper methods of Devise and CanCanCan at my disposal.
<% if user_signed_in? && ... %> # current_user has already created a review for this movie
<%= link_to "Edit Review", edit_movie_review_path(#movie, review) %>
<% else %>
<%= link_to "Write a Review", new_movie_review_path %>
<% end %>
Also: Is there any way to improve the lookup in my has_reviewed? method? I feel like there's a better way to write it but can't determine the most appropriate fix.
Why not use a validation:
#app/models/review.rb
class Review < ActiveRecord::Base
validates :movie_id, uniqueness: { scope: :user_id, message: "You've reviewed this movie!" }
end
This is considering your review model belongs_to :movie
You could also use an ActiveRecord callback:
#app/models/review.rb
class Review < ActiveRecord::Base
before_create :has_review?
belongs_to :user, inverse_of: :reviews
belongs_to :movie
def has_review?
return if Review.exists?(user: user, movie_id: movie_id)
end
end
#app/models/user.rb
class User < ActiveRecord::Base
has_many :reviews, inverse_of: :user
end
Is there any way to improve the lookup in my has_reviewed? method?
def has_reviewed?
redirect_to album_reviews_path, notice: "You've already written a review for this album." if current_user.reviews.exists?(movie: #movie)
end
Why not make a has_reviewed? method on your User class?
e.g.
def has_reviewed?(reviewable)
# query in here
end
Then you should be able use that just fine in your controller and your views.
You will want to do this for both new and create. Otherwise a savvy user would be able to run a post that would get past your new action.
I would put the link_to in either a helper or a presenter object. It would generally look like this.
def create_or_edit_review_path(movie, current_user)
return '' if current_user.blank?
if current_user.review.present?
#Generate review edit link
else
#generate new link
end
end
After that in all of your views it would just be
<%= create_or_edit_review_path(#movie, current_user) %>
Then in your controller for both new and create you could do either a before action or just redirect on each.
before_action :enforce_single_review, only: [:create, :new]
def enforce_single_review
if current_user.review.present?
redirect_to review_path(current_user.review)
end
end
Here's what I came up with:
I created an instance method to retrieve a user's movie review using the find_by method on the Review model:
class User < ActiveRecord::Base
....
def movie_review(album)
Review.find_by(user_id: self, album_id: album)
end
end
This method also comes in handy when setting up my callback:
class ReviewsController < ApplicationController
before_action :limit_review, only: [:new, :create]
....
private
def limit_review
user_review = current_user.movie_review(#movie)
if user_review.present?
redirect_to edit_movie_review_path(#movie, user_review)
end
end
end
Created a helper method for showing the appropriate link to edit or create a review. Big thanks to Austio and his suggestion:
module ReviewsHelper
def create_or_edit_review_path(movie)
user_review = current_user.movie_review(movie) if user_signed_in?
if user_signed_in? && user_review.present?
link_to "Edit review", edit_movie_review_path(movie, user_review)
else
link_to "Write a review", new_movie_review_path
end
end
end
And at last this is how I call the helper in my view template(s):
....
<%= create_or_edit_review_path(#album) %>
I have been trying to build an app offering discounted vacation trips such that:
(1) a user(travel agent) can compose a trip by combining hotels (hotel chains) and cities
(2) a user(regular user) can review hotels and cities, s/he has already visited.
(3) another user can evaluate how good the deal is with respect to the country and hotel the travel agent will have him/her stay.
The models look like this
class User < ActiveRecord::Base
has_many :trips
has_many :reviews
end
class Trip < ActiveRecord::Base
belongs_to :user
belongs_to :hotel
belongs_to :city
end
class Hotel < ActiveRecord::Base
belongs_to :city
has_many :reviews, as: :reviewable
end
class City < ActiveRecord::Base
has_many :hotels
has_many :reviews, as: :reviewabel
end
class Review < ActiveRecord::Base
belongs_to :user
belongs_to :reviewable, polymorphic: true
end
The problem is I can figure out how to create the controllers for Hotel and City because they are only created in the context of a makeshift trip. I checked the rails casts on nested forms and the use of accepts_nested_attributes_for but I can't seem to get it right.
Note: the reason why I separated the hotels and the cities is to be able to retrieve the reviews independently. Such that Say I enjoyed my stay at the Four Seasons in Toronto but not the one in NY. - because of the cities/hotels (=> accommodating the case where I didn’t enjoy it because the hotel was crap and the one where I didn’t because the city was)
Note 2: I understand it doesn’t make much sense to seperate hotels and cities in this example - I made a mistake in self-appointing the tutorial. But the problem has been haunting me, what if it was an delivery order instead with entree/meal/dinner instead of hotels and cities, or restaurant chains and neighborhoods.
Any help is appreciated. Thank you
Edit
Edited after Settheline’s comment.
I mean the create actions for cities and hotels only exist in the context of a Trip create action.
Trip has 2 attributes: title & description: It’s only then that I “log” the itinerary. Here’s what my controllers look like to give you a better idea
class TripsController < ApplicationController
before_action :signed_in_user
def show
#trip = Trip.find(params[:id])
end
def index
#trips = current_user.Trip.all
end
def new
#trip = Trip.new
end
def create
# #trip = Trip.new(trip_params)
#trip = current_user.trips.build(trip_params)
if #trip.save
flash[:success] = "Your trip was successfully published!"
redirect_to #trip
else
render 'new'
end
end
def edit
end
def update
if #trip.update_attributes(trip_params)
flash[:success] = "Trip was updated"
redirect_to #trip
else
render 'edit'
end
end
def destroy
Trip.find(params[:id]).destroy
flash[:success] = "trip was deleted. Thank you"
redirect_to #user #root_url
end
private
def trip_params
params.require(:trip).permit(:title, :description)
end
end
class CitiesController < ApplicationController
before_action :signed_in_user
def create
#city = City.new(city_params)
if #city.save
# flash[:success] = ""
else
render 'new'
end
end
# def destroy
# City.find(params[:id]).destroy
# flash[:success] = “City was deleted."
# redirect_to root_url
# end
private
def city_params
params.require(:city).permit(:name, :province, :country)
end
end
class HotelsController < ApplicationController
before_action :signed_in_user
def create
#similar to city
end
def destroy
#similar to city
end
private
def hotel_params
params.require(:hotel).permit(:name, :address,
:management_contact,
:city_id)
end
end
And here’s the problem:
I want to have/add create forms within the trip one in
sample_app/app/views/trips/new.html.erb
<% provide(:title, 'New Trip') %>
<h1>New Trip</h1>
<div class="row">
<div class="span6 offset3">
<%= form_for(#trip) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.text_field :title, placeholder: "Type in a title" %>
<%= f.text_field :description, placeholder: "Any additional info." %>
<%= f.submit "Publish", class: "btn btn-large btn-primary" %>
<% end %>
</div>
</div>
accepts_nested_attributes_for allows you to save attributes on associations. Although you do have associations in your models it doesn't necessarily mean that you need to use accepts_nested_attributes_for. It depends on how the code flows through your controllers.
Simple Example
For example, you would probably want to allow your users to view their trips and reviews. First you'll need a method to get the current user:
users_controller.rb
class ApplicationController < ActionController::Base
def current_user
#current_user ||= User.find(session[:user_id])
end
end
This method will be inherited by all of your controllers and allow them to get the current user. (There are many solutions out there for getting the current user, this is definitely not a good solution but it is OK for demonstration purposes).
Trips & Reviews
Now you can create some controllers for the current user to view their trips and reviews:
trips_controller.rb
class TripsController < ApplicationController
def index
#trips = current_user.trips.all
end
end
reviews_controller.rb
class ReviewsController < ApplicationController
def index
#reviews = current_user.reviews.all
end
end
Now you have some controller actions displaying the trips/reviews for the current user. I think this example demonstrates how you can create your controllers and that accepts_nested_attributes_for is not necessarily required.