undefined method `team_id' - Ruby on Rails - ruby-on-rails

The error is undefined method 'team_id' for Player:0x007fb5f41f3838.
I am trying to edit players and I am not able to do that because of an undefined method.
My guess is it has something to do with my relations. I am learning relations between models so they may not be correct.
This is my Player Model
class Player < ActiveRecord::Base
validates_length_of :description, :maximum=>4000
has_many :descriptions, through: :fouls
has_many :fouls, as: :foul_by_id
has_many :fouls, as: :foul_on_id
belongs_to :team
end
This is my Player Controller
class PlayersController < ApplicationController
before_action :authenticate_user!
before_action :most_recent_fouls
def index
#players = Player.all
end
def show
#player = Player.find(params[:id])
end
def new
#player = Player.new
end
def create
#player = Player.new(players_params)
if #player.save
redirect_to(:action => "index")
else
render("new")
end
end
def edit
#player = Player.find(params[:id])
end
def update
#player = Player.find(params[:id])
if #player.update_attributes(players_params)
redirect_to(:action => "show", :id => #player.id)
else
render("index")
end
end
def destroy
player = Player.find(params[:id]).destroy
redirect_to(:action => "index")
end
private
def players_params
params.require(:player).permit(:name, :number, :position, :bios, :descriptions, :team_id)
end
end
Because of my gut saying that it has to do with relations, here is my Team Model
class Team < ActiveRecord::Base
has_many :players
validates :name, presence: true
end
My migration table for Player
class CreatePlayers < ActiveRecord::Migration
def change
create_table :players do |p|
p.string :name
p.string :number
p.string :position
p.string :bio
p.string :description
p.integer :team_id
p.timestamps
end
end
end
Any help is appreciated. Please explain your answer. Tell me if you need any more code to be displayed.

Related

Ruby on Rails assign company_id and job_id in models

Have three models: Company, Job and JobApplications. When submitting the job form, the company_id and job_id are showing up as nil in the rails console. What's the best way to assign both company_id and job_id values for each job created by a company?
I've added the company_id and job_id to the companies and jobs tables. Within the create method of my jobs model, I've assigned #company_id to the job params and company_id and job_id are still showing as nil after creating a job.
Controller Actions
class CompaniesController < ApplicationController
def new
#company = current_user.build_company
end
def create
#job = Job.new
#company = Company.new(company_params)
end
private
def set_company
#company = Company.find(params[:id])
end
def company_params
params.require(:company).permit(:avatar, :name, :website, :about)
end
class JobsController < ApplicationController
def new
#job = Job.new(:company_id => params[:id])
#company_id = params[:job][:company_id]
end
def create
# #job = current_user.jobs.build(job_params)
#job = Job.find(params[:job_id])
# #company = #job.company
#job = Job.create(job_params.merge(user: current_user, company_id: current_user, job_id: #job))
#company_id = params[:job][:company_id]
end
private
def set_job
#job = Job.find_by(id: params[:id])
if #job.nil?
redirect_to jobs_path
end
end
def job_params
params.require(:job).permit(:company_name, :company_website, :company_description, :company_avatar, :title, :location, :salary, :job_author, :remote_role, :job_type, :rounds_of_interviews, :start_date, :qualifications, :description, :benefits, :job_id)
end
class JobApplicationsController < ApplicationController
def create
#job_application = JobApplication.new(job_application_params)
#job_application.user_id = current_user.id
end
private
def set_job
#job = Job.find(params[:job_id])
# self.job_id
end
def job_application_params
params.permit(:first_name, :last_name, :email, :phone, :attachment, :work_for_any_employer, :require_visa_sponsorship)
end
Models
class Company < ApplicationRecord
has_many :conversations
has_many :jobs
has_many :job_applications, through: :jobs
end
class Job < ApplicationRecord
belongs_to :user
belongs_to :company, optional: true
has_many :job_applications, dependent: :destroy
end
class JobApplication < ApplicationRecord
belongs_to :user
belongs_to :job
validates_uniqueness_of :user_id, scope: :job_id
end

undefined method `reviews' for #<Post:0x007fa207cb7c70>

I'm following a tutorial on how to implement reviews for my rails app, users can add reviews for posts. But when i click add new review i get 'NoMethodError in Reviews#new'
Reviews controller
class ReviewsController < ApplicationController
before_action :find_post
def new
#review = Review.new
end
def create
#review = Review.new(review_params)
#review.post_id = #post.id
#review.user_id = current_user.id
if #review.save
redirect_to post_path(#post)
else
render 'New'
end
end
private
def review_params
params.require(:review).permit(:rating, :comment)
end
def find_post
#post = Post.friendly.find(params[:post_id])
end
end
Review model
class Review < ApplicationRecord
belongs_to :post
belongs_to :user
end
Post model
class Post < ApplicationRecord
extend FriendlyId
belongs_to :user
friendly_id :title, use: :slugged
validates_presence_of :title , :description
end
It looks like you forgot has_many :reviews in your Post model.

Rails Association Undefined method error

I would like to add "category" function.
I associated article.rb and category.rb.
However, undefined method `categories' for nil:NilClass was present.
I have no idea.If you know any solution, please tell me.
Index.html.erb
<% unless #article.categories.blank? %>
<% #articles.categories.each do |category|%>
<%= link_to category.name,article_path(category_id:category.id)%>
<%end%>
<%end%>
article.rb
class Article < ApplicationRecord
scope :from_category, -> (category_id) { where(id: article_ids = ArticleCategory.where(category_id: category_id).select(:article_id))}
validates :title, presence: true
validates :content, presence: true
mount_uploader :image,ImageUploader
has_many :categories, through: :article_categories
has_many :article_categories, dependent: :destroy
def save_categories(tags)
current_tags = self.categoires.pluck(:name) unless self.categories.nil?
old_tags = current_tags - tags
new_tags = tags - current_tags
old_tags.each do |old_name|
self.categories.delete Category.find_by(name:old_name)
end
new_tags.each do |new_name|
article_category = Category.find_or_create_by(name:new_name)
self.categories << article_category
end
end
end
category.rb
class Category < ApplicationRecord
validates :name,presense: true,length:{maximum:50}
has_many :articles,through: :article_categories
has_many :article_categories,dependent: :destroy
end
article_category.rb
class ArticleCategory < ApplicationRecord
belongs_to :article
belongs_to :category
validates :article_id,presense:true
validates :category_id,presense:true
end
articles_controller.rb
class ArticlesController < ApplicationController
before_action :set_post, only: [:show,:edit,:update]
before_action :authenticate_user!, :except => [:index,:show]
before_action :set_article_tags_to_gon, only: [:edit]
def index
if params[:category_id]
#selected_category = Category.find(params[:category_id])
#articles= Article.from_category(params[:category_id]).page(params[:page])
else
#articles= Article.all.page(params[:page])
end
#articles = Article.page params[:page]
end
def show
end
def new
#article = Article.new
end
def create
#article = Article.new(article_params)
if #article.save
redirect_to articles_path
else
render 'articles/new'
end
end
def edit
#category_list = #article.categories.pluck(:name).join(",")
end
def update
if #article.update(article_params)
redirect_to articles_path
else
redirect_to 'edit'
end
end
private
def article_params
params[:article].permit(:title,:content,:image,:tag_list,:category)
end
def set_post
#article = Article.find(params[:id])
end
error message
You're calling categories on a nil object, in this case #article. Did you mean to call it on #articles?
If not, you will need to define #article in the index action of your controller.

DB rolls back on create action

I'm trying to create a form with a series of checks to prevent duplicates during the simultaneous creation of three model records: one for the parent (assuming it doesn't exist), one for its child (assuming it doesn't exist), and one for a join table between the child and the User (to allow the User to have their own copy of the Song object).
In the current state of the code, The checks seemingly pass, but
the server logs show ROLLBACK, and nothing gets saved
to the database EXCEPT the parent object (artist).
When I try to use the ids of the object, I get the error undefined method id for nil:NilClass, or "couldn't find object without an ID".
The following code is in my controller:
class SongsController < ApplicationController
before_action :authenticate_user!
def create
#artist = Artist.find_by(name: params[:artist][:name].strip.titleize) #look for the artist
#song = Song.find_by(title: params[:artist][:songs_attributes]["0"][:title].strip.titleize)
if #artist.present? && #song.present?
#user_song = current_user.user_songs.find(#song_id)
if #user_song.present?
render html: "THIS SONG IS ALREADY IN YOUR PLAYLIST"
render action: :new
else
#user_song = UserSong.create(user_id: current_user.id, song_id: #song.id)
redirect_to root_path
end
elsif #artist.present? && !#song.present?
#song = #artist.songs.build(title: params[:artist][:songs_attributes]["0"][:title].strip.titleize, lyrics: params[:artist][:songs_attributes]["0"][:lyrics].strip)
#user_song = UserSong.create(user_id: current_user.id, song_id: #song.id)
redirect_to root_path
elsif !#artist.present?
#artist = Artist.create(name: params[:artist][:name].strip.titleize)
#song = #artist.songs.build(title: params[:artist][:songs_attributes]["0"][:title].strip.titleize, lyrics: params[:artist][:songs_attributes]["0"][:lyrics].strip)
#user_song = UserSong.create(user_id: current_user.id, song_id: #song.id)
redirect_to root_path
else
render html: "SOMETHING WENT WRONG. CONTACT ME TO LET ME KNOW IF YOU SEE THIS MESSAGE"
end
end
def index
#songs = Song.all
end
def new
#artist = Artist.new
#artist.songs.build
#user_song = UserSong.new(user_id: current_user.id, song_id: #song_id)
end
def show
#song_id = params["song_id"]
#song = Song.find(params[:id])
end
def destroy
UserSong.where(:song_id => params[:id]).first.destroy
flash[:success] = "The song has been from your playlist"
redirect_to root_path
end
def edit
#song = Song.find(params[:id])
#artist = Artist.find(#song.artist_id)
end
def update
end
private
def set_artist
#artist = Artist.find(params[:id])
end
def artist_params
params.require(:artist).permit(:name, songs_attributes: [:id, :title, :lyrics])
end
def set_song
#song = Song.find(params["song_id"])
end
end
The models:
class Artist < ApplicationRecord
has_many :songs
accepts_nested_attributes_for :songs, reject_if: proc { |attributes| attributes['lyrics'].blank? }
end
class Song < ApplicationRecord
belongs_to :artist
has_many :user_songs
has_many :users, :through => :user_songs
end
class UserSong < ApplicationRecord
belongs_to :song
belongs_to :user
end
Sorry if I haven't abstracted enough. Not really sure how, given that there's no error message, just a rollback (without any validations present in any of the controllers).
Thanks to #coreyward and his pointing out of the fat-model skinny-controller lemma (never knew that was a thing), I was able to cut the code down and arrive at a solution immediately. In my models, I used validates_uniqueness_of and scope in order to prevent duplication of records. In my controller, I used find_or_create_by to seal the deal.
To whom it may concern, the final code is as follows:
class SongsController < ApplicationController
before_action :authenticate_user!
def create
#artist = Artist.find_or_create_by(name: params[:artist][:name].strip.titleize)
#song = #artist.songs.find_or_create_by(title: params[:artist][:songs_attributes]["0"][:title].strip.titleize) do |song|
song.lyrics = params[:artist][:songs_attributes]["0"][:lyrics].strip
end
#user_song = current_user.user_songs.find_or_create_by(song_id: #song.id) do |user_id|
user_id.user_id = current_user.id
end
redirect_to root_path
end
class Song < ApplicationRecord
validates_uniqueness_of :title, scope: :artist_id
belongs_to :artist
has_many :user_songs
has_many :users, :through => :user_songs
end
class Artist < ApplicationRecord
validates_uniqueness_of :name
has_many :songs
accepts_nested_attributes_for :songs, reject_if: proc { |attributes| attributes['lyrics'].blank? }
end
class UserSong < ApplicationRecord
validates_uniqueness_of :song_id, scope: :user_id
belongs_to :song
belongs_to :user
end

Modeling Event Booking Process

New to stack! so Hello there ! I'm making a sample event booking app, that has event check out using stripe.
My set up is below
class Event < ActiveRecord::Base
belongs_to :user
has_many :tickets, :inverse_of => :event, dependent: :destroy
end
class Ticket < ActiveRecord::Base
belongs_to :event, :inverse_of => :tickets
end
class Booking < ActiveRecord::Base
belongs_to :event
belongs_to :ticket, :inverse_of => :bookings
has_one :sale, :inverse_of => :booking
end
class Sale < ActiveRecord::Base
belongs_to :booking, :inverse_of => :sale
belongs_to :ticket
end
class BookingsController < ApplicationController
before_filter :load_event
before_filter :load_ticket
def index
#bookings = #event.bookings
end
def new
#booking = Booking.new
end
private
def load_event
#event = Event.find(params[:event_id])
end
def load_ticket
#ticket = #event.tickets.find(params[:ticket_id])
end
def booking_params
params.require(:booking).permit(:buyer_name, :phone, :address, :order_quantity,:total_amount)
end
end
class TransactionsController < ApplicationController
before_filter :load_event
before_filter :load_booking
before_filter :load_ticket
def new
end
def pickup
#sale = Sale.find_by!(guid: params[:guid])
#booking = #sale.booking
end
def complete
#sale = Sale.find_by!(guid: params[:guid])
#booking = #sale.booking
end
if sale.save
StripeCharger.perform_async(sale.guid)
render json: { guid: sale.guid }
else
errors = sale.errors.full_messages
render json: {
error: errors.join(" ")
}, status: 400
end
end
def status
sale = Sale.find_by!(guid: params[:guid])
render json: { status: sale.state }
end
private
def load_event
#event = Event.find(params[:event_id])
end
def load_booking
#booking = #event.bookings.find(params[:booking_id])
end
def load_ticket
#ticket = #booking.ticket.find(params[:ticket_id])
end
end
#Stripe Checkout Routes
I left out a view minimal details within the models . But basically What I am trying to do is have a user enter Name, and quantity of the ticket and from submitin the booking redirect to the transaction new, in which I can carry out the sale model with Stripe Check out.
My ultimate goal of everything is to get the bookings quantity input multiplied with the ticket price to get a total amount to carry through Stripe. Do anyone have any suggestions on how to improve this break down. Of modeling a events, tickets, bookings to check out type of example. Sorry if how I'm breaking it down is noobish, I'm attempting to wrap my head around accomplishing this.
In transaction controller you don't need find on #booking.ticket
def load_ticket
#ticket = #booking.ticket.find(params[:ticket_id])
end
Since #booking has only one ticket, you just need #booking.ticket

Resources