In Ruby on Rails I have a user models and a jobs model joined through a different model called applicants. I have a button for the users when they want to "remove their application for this job" but I don't know how to remove the specific user, and for that matter I don't know if I'm doing a good job at adding them either (I know atleast it works).
user.rb
class User < ActiveRecord::Base
...
has_many :applicants
has_many:jobs, through: :applicants
end
job.rb
class Job < ActiveRecord::Base
...
has_many :applicants
has_many:users, through: :applicants
end
applicant.rb
class Applicant < ActiveRecord::Base
belongs_to :job
belongs_to :user
end
when someone applies for a job my jobs controller is called:
class JobsController < ApplicationController
...
def addapply
#job = Job.find(params[:id])
applicant = Applicant.find_or_initialize_by(job_id: #job.id)
applicant.update(user_id: current_user.id)
redirect_to #job
end
...
end
Does that .update indicate that whatever is there will be replaced? I'm not sure if I'm doing that right.
When someone wants to remove their application I want it to go to my jobs controller again but I'm not sure what def to make, maybe something like this?
def removeapply
#job = Job.find(params[:id])
applicant = Applicant.find_or_initialize_by(job_id: #job.id)
applicant.update(user_id: current_user.id).destroy
redirect_to #job
end
does it ave to sort through the list of user_ids save them all to an array but the one I want to remove, delete the table then put them all back in? I'm unsure how this has_many works, let alone has_many :through sorry for the ignorance!
thanks!
Let's assume the user will want to remove their own application. You can do something like this:
class UsersController < ApplicationController
def show
#applicants = current_user.applicants # or #user.find(params[:id]), whatever you prefer
end
end
class ApplicantsController < ApplicationController
def destroy
current_user.applications.find(params[:id]).destroy
redirect_to :back # or whereever
end
end
And in your view:
- #applicants.each do |applicant|
= form_for applicant, method: :delete do |f|
= f.submit
Don't forget to set a route:
resources :applicants, only: :destroy
Some observations, I would probably name the association application instead of applicant. So has_many :applications, class_name: 'Applicant'.
Related
newbie here...
I am trying to create an events registration page where anybody can register for an event without logging into the system.
My problem is trying to figure out how to tie the registration info to the specific event. I've created all the associations but can't figure how to tell the db that the person is registering for a specific event.
Here are my associations:
class Event < ActiveRecord::Base
belongs_to :user
has_many :event_regs
has_many :regs, through: :event_regs
class Reg < ActiveRecord::Base
has_many :event_regs
class Reg < ActiveRecord::Base
has_many :event_regs
Thanks in advance
Newbie here
Welcome!
Here's what you'll need:
#app/models/event.rb
class Event < ActiveRecord::Base
has_many :registrations
end
#app/models/registration.rb
class Registration < ActiveRecord::Base
belongs_to :event
end
This will allow you to use the following:
#config/routes.rb
resources :events do #-> url.com/events/:id
resources :registrations #-> url.com/events/:event_id/registrations/
end
#app/controllers/registrations_controller.rb
class RegistrationsController < ApplicationController
def new
#event = Event.find params[:event_id]
#registration = #event.registration.new
end
def create
#event = Event.find params[:event_id]
#registration = #event.registration.new registration_params
end
private
def registration_params
params.require(:registration).permit(:all, :your, :params)
end
end
This will create a new registration record in your db, associating it with the Event record you've accessed through the route.
--
From this setup, you'll be able to use the following:
#app/controllers/events_controller.rb
class EventsController < ApplicationController
def show
#event = Event.find params[:id]
end
end
#app/views/events/show.html.erb
<% #event.registrations.each do |registration| %>
# -> output registration object here
<% end %>
Foreign Keys
In order to understand how this works, you'll be best looking at something called foreign keys...
This is a relational database principle which allows you to associate two or more records in different database tables.
Since Rails is designed to work with relational databases, each association you use will require the use of a "foreign key" in some respect.
In your case, I would recommend using a has_many/belongs_to relationship:
You'll need to make sure you add the event_id column to your registrations database.
How can I redirect to the next lesson that does not have userLesson (problem is lessons belongs to a course through a chapter)
Models:
class Course
has_many :lessons, through: :chapters
end
class Lesson
belongs_to :chapter
has_one :lecture, through: :chapter
end
class User
has_many :user_lessons
end
class UserLesson
#fields: user_id, lesson_id, completed(boolean)
belongs_to :user
belongs_to :lesson
end
class Chapter
has_many :lessons
belongs_to :lecture
end
here user_lessons_controller:
class UserLessonsController < ApplicationController
before_filter :set_user_and_lesson
def create
#user_lesson = UserLession.create(user_id: #user.id, lession_id: #lesson.id, completed: true)
if #user_lesson.save
# redirect_to appropriate location
else
# take the appropriate action
end
end
end
I want to redirect_to the next lesson that has not the UserLesson when saved. I have no idea how to do it as it belongs_to a chapter. Please help! Could you please help me with the query to write...
Here is the answer for your question:
Inside your user_lessons_controller:
def create
#user_lesson = UserLession.create(user_id: #user.id, lession_id: #lesson.id, completed: true)
if #user_lesson.save
#You have to determine the next_lesson object you want to redirect to
#ex : next_lessons = current_user.user_lessons.where(completed: false)
#This will return an array of active record UserLesson objects.
#depending on which next_lesson you want, you can add more conditions in `where`.
#Say you want the first element of next_lessons array. Do
##next_lesson = next_lessons.first
#after this, do:
#redirect_to #next_lesson
else
#redirect to index?? if so, add an index method in the same controller
end
end
This code will only work if you define show method in your UserLessonsController and add a show.html in your views.
Also, in config/routes.rb, add this line : resources :user_lessons.
I'm learning Rails (4.2 installed) and working on a social network simulation application.
I have setup an one to many relation between Users and Posts and now I'm trying to add also Comments to posts. After multiple tries and following the documentation on rubyonrails.org I ended up with the following setup:
User Model
has_many :posts, dependent: :destroy
has_many :comments, through: :posts
Post Model
belongs_to :user
has_many :comments
Comment Model
belongs_to :user
The comment is initiated from the Post show page, so the
Post Controller has:
def show
#comment = Comment.new
end
Now the question is: in Comments Controller , what is the correct way to create a new record.
I tried the below and many others, but without success.
def create
#comment = current_user.posts.comment.new(comment_params)
#comment.save
redirect_to users_path
end
(current_user is from Devise)
Also, afterwards, how can I select the post corresponding to a comment?
Thank you
You'll want to create a relation on Post, letting each Comment know "which Post it relates to." In your case, you'll likely want to create a foreign key on Comment for post_id, then each Comment will belong_to a specific Post. So, you'd add belongs_to :post on your Comment model.
So, your models become:
class User < ActiveRecord::Base
has_many :posts, dependent: :destroy
has_many :comments, through: :posts
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments
end
class Comments < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
Then, to create a Comment, you would want to do one of two things in your controller:
Load the Post corresponding to the Comment you are creating via the URI as a parameter.
Pass the Post ID along in the form in which calls the create method on Comment.
I personally prefer loading the Post from a parameter in the URI, as you'll have less checking to do as far as authorization for can the Comment in question be added to the Post - e.g. think of someone hacking the form and changing the ID for the Post that the form originally sets.
Then, your create method in the CommentsController would look like this:
def create
#post = Post.find(post_id_param)
# You'll want authorization logic here for
# "can the current_user create a Comment
# for this Post", and perhaps "is there a current_user?"
#comment = #post.comments.build(comment_params)
if #comment.save
redirect_to posts_path(#post)
else
# Display errors and return to the comment
#errors = #comment.errors
render :new
end
end
private
def post_id_param
params.require(:post_id)
end
def comment_params
params.require(:comment).permit(...) # permit acceptable Comment params here
end
Change your Comment model into:
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user, through: :post
end
Pass the post_id from view template:
<%= hidden_field_tag 'post_id', #post.id %>
Then change your create action:
def create
#post = Post.find(params[:post_id])
#comment = #post.comments.build(comment_params)
#comment.user = current_user
redirect_to post_path(#post)
end
I'm trying to add a 'Collections' model to group Posts so that any user can add any Post they like to any Collection they've created. The Posts will have already been created by a different user. We are just letting other users group these posts in their own Collections. Basically like bookmarking.
What is the cleanest, and most Rails-ey-way of doing this?
I've created the model and run through the migration and what not. Also I've already created proper views for Collection.
rails g model Collection title:string user_id:integer
collections_controller.rb
class CollectionsController < ApplicationController
def index
#collections = current_user.collections.all
end
def show
#collection = Collection.all
end
def new
#collection = Collection.new
end
def create
#collection = current_user.collections.build(collection_params)
if #collection.save
redirect_to #collection, notice: 'saved'
else
render action: 'new'
end
end
def update
end
private
def collection_params
params.require(:collection).permit(:title)
end
end
collection.rb
class Collection < ActiveRecord::Base
belongs_to :user
has_many :posts
validates :title, presence: true
end
post.rb
has_many :collections
It seems like has_many or has_and_belongs_to_many associations are not correct? Should I be creating another model to act as an intermediary to then use
has_many :collections :through :collectionList?
If my association is wrong, can you explain what I need to change to make this work?
Also the next part in this is since this is not being created when the Post or Collection is created, I'm not sure the best way to handle this in the view. What is the best way to handle this, keeping my view/controller as clean as possible? I just want to be able to have a button on the Post#Show page that when clicked, allows users to add that post to a Collection of their own.
In such case you should use or has_and_belongs_to_many or has_many :through association. The second one is recommended, because it allows more flexibility. So now you should:
Create new model PostsCollections
rails g model PostsCollections post_id:integer collection_id:integer
and migrate it
Set correct model associations:
Something like:
class Post < ActiveRecord::Base
has_many :posts_collections
has_many :categories, through: :posts_collections
end
class Collection < ActiveRecord::Base
has_many :posts_collections
has_many :posts, through: :posts_collections
end
class PostsCollections < ActiveRecord::Base
belongs_to :post
belongs_to :collection
end
Then you'll be able to use
#collection.first.posts << #post
And it will add #post to #collection's posts
To add a post to a collection from view
Add a new route to your routes.rb, something like:
resources :collections do # you should have this part already
post :add_post, on: :member
end
In your Collections controller add:
def add_post
#post = Post.find(params[:post_id])
#collection = Collection.find(params[:id])
#collection.posts << #post
respond_to do |format|
format.js
end
end
As for views, you'll have to create a form to show a collection select and button to add it. That form should make POST method request to add_post_collection_path(#collection) with :post_id parameter.
You can read more explanations of how rails associations work in Michael Hartl's tutorial, because that subject is very wide, and can't be explained with short answer.
So, I've read in some book about tip "Use model association", which encourages developers to use build methods instead of putting ids via setters.
Assume you have multiple has_many relationships in your model. What's best practise for creating model then ?
For example, let's say you have models Article, User and Group.
class Article < ActiveRecord::Base
belongs_to :user
belongs_to :subdomain
end
class User < ActiveRecord::Base
has_many :articles
end
class Subdomain < ActiveRecord::Base
has_many :articles
end
and ArticlesController:
class ArticlesController < ApplicationController
def create
# let's say we have methods current_user which returns current user and current_subdomain which gets current subdomain
# so, what I need here is a way to set subdomain_id to current_subdomain.id and user_id to current_user.id
#article = current_user.articles.build(params[:article])
#article.subdomain_id = current_subdomain.id
# or Dogbert's suggestion
#article.subdomain = current_subdomain
#article.save
end
end
Is there a cleaner way ?
Thanks!
This should be a little cleaner.
#article.subdomain = current_subdomain
The only thing I can think of is merging the subdomain with params:
#article = current_user.articles.build(params[:article].merge(:subdomain => current_subdomain))