Could not find the association :catorizations in model - ruby-on-rails

I'm losing a lot of sleep over this! Can't seem to figure out why the association aren't there...ANY help is well appreciated
Could not find the association :catorizations in model Question
The first line is where the error is point to
<% if #question.categories.present? %>
Categories (<%= #question.categories.count %>):
<%= #question.categories.map(&:title).join(", ") %>
<% end %>
Models
class Question < ActiveRecord::Base
belongs_to :user
has_many :answers, dependent: :destroy
has_many :categorizations, dependent: :destroy
has_many :categories, through: :catorizations
end
class Categorization < ActiveRecord::Base
belongs_to :category
belongs_to :question
end
class Category < ActiveRecord::Base
has_many :categorizations, dependent: :destroy
has_many :questions, through: :categorizations
end
class Answer < ActiveRecord::Base
belongs_to :question
validates_presence_of :body
scope :ordered_by_creation, -> { order("created_at DESC")}
end
QuestionController
class QuestionsController < ApplicationController
before_action :authenticate_user!, except: [:index, :show, :home]
before_action :find_question, only: [:edit, :update, :destroy, :vote]
# GET /questions
# GET /questions.json
def index
if signed_in?
# #question = Question.find(params[:question_id] || params[:id])
#questions = Question.all
else
respond_to do |format|
format.html { redirect_to root_path, notice: 'Must Sign In To Start Having Fun.' }
format.json { head :no_content }
end
end
end
def home
end
# GET /questions/1
# GET /questions/1.json
def show
#question = Question.find(params[:question_id] || params[:id])
#answer = Answer.new
# #answers = #qustion.answers.ordered_by_creation
end
# GET /questions/new
def new
#question = Question.new
end
def vote
value = params[:type] == "up" ? 1 : -1
#question = Question.find(params[:id])
#question.add_or_update_evaluation(:votes, value, current_user)
redirect_to :back, notice: "Thank you for voting!"
end
# GET /questions/1/edit
def edit
#question = Question.find(params[:id])
end
# POST /questions
# POST /questions.json
def create
#question = current_user.questions.new(question_params)
# #question = Question.new(question_params)
respond_to do |format|
if #question.save
format.html { redirect_to #question, notice: 'Question was successfully created.' }
format.json { render :show, status: :created, location: #question }
else
format.html { render :new }
format.json { render json: #question.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /questions/1
# PATCH/PUT /questions/1.json
def update
respond_to do |format|
if #question.update(question_params)
format.html { redirect_to #question, notice: 'Question was successfully updated.' }
format.json { render :show, status: :ok, location: #question }
else
format.html { render :edit }
format.json { render json: #question.errors, status: :unprocessable_entity }
end
end
end
# DELETE /questions/1
# DELETE /questions/1.json
def destroy
#question.destroy
respond_to do |format|
format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_question
#question = Question.find(params[:id])
end
def find_question
#question = current_user.questions.find_by_id(params[:id])
redirect_to root_path, alert: "Access Denied" unless #question
end
# Never trust parameters from the scary internet, only allow the white list through.
def question_params
params.require(:question).permit(:question, :question_id, :vote, {category_ids: []})
end
end
Finally my Schema if that helps
Schema
create_table "answers", force: :cascade do |t|
t.text "body"
t.integer "question_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
end
add_index "answers", ["question_id"], name: "index_answers_on_question_id"
add_index "answers", ["user_id"], name: "index_answers_on_user_id"
create_table "categories", force: :cascade do |t|
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "categorizations", force: :cascade do |t|
t.integer "category_id"
t.integer "question_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "categorizations", ["category_id"], name: "index_categorizations_on_category_id"
add_index "categorizations", ["question_id"], name: "index_categorizations_on_question_id"
create_table "questions", force: :cascade do |t|
t.string "question"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "question_id"
t.integer "user_id"
end

Could not find the association :catorizations in model Question
You have a typo in Question model
This
has_many :categories, through: :catorizations
should be
has_many :categories, through: :categorizations

Related

RAILS - ActiveModel::MissingAttributeError - Possible issue with how array is being stored?

I'm getting a missing attribute error when trying to automatically create a InvoiceAppCollection when an Invoice is created.
This is the error that I'm getting:
ActiveModel::MissingAttributeError in InvoicesController#create
can't write unknown attribute app_collection_id
From what I've looked up when other people have this issue it has to do with the relationships between the models, but I'm pretty sure that I have the models communicating to each other properly.
The function I wrote to create the invoice app collection is in the invoice controller
def create_invoice_app_collection
InvoiceAppCollection.create(
po_number: #invoice.po_number,
app_collection: #invoice.app_collection
)
end
Here are my models and controllers. I also have the select box where the app_collections are being selected at the bottom.
Here are the Models
class AppCollection < ApplicationRecord
belongs_to :company
acts_as_tenant(:company)
has_many :invoice_app_collections
has_many :invoices, through: :invoice_app_collections
validates :name, uniqueness: true
end
class Invoice < ApplicationRecord
belongs_to :company
acts_as_tenant(:company)
has_many :invoice_app_collections
has_many :app_collections, through: :invoice_app_collections
validates :expiration, on: [:create, :update, :save], :presence => true
end
class InvoiceAppCollection < ApplicationRecord
belongs_to :app_collection
belongs_to :invoice
belongs_to :company
acts_as_tenant(:company)
accepts_nested_attributes_for :app_collection
end
AppCollectionController
class AppCollectionsController < ApplicationController
before_action :set_app_collection, only: %i[ show edit update destroy ]
def index
AppCollections = app_collection.all
end
def create
#app_collection = app_collection.new(app_collection_params)
respond_to do |format|
if #app_collection.save
format.html { redirect_to app_collection_url(#app_collection), notice: "App collection was successfully created." }
format.json { render :show, status: :created, location: #app_collection }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #app_collection.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #app_collection.update(app_collection_params)
format.html { redirect_to app_collection_url(#app_collection), notice: "App collection was successfully updated." }
format.json { render :show, status: :ok, location: #app_collection }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: #app_collection.errors, status: :unprocessable_entity }
end
end
end
def destroy
#app_collection.destroy
respond_to do |format|
format.html { redirect_to app_collections_url, notice: "app collection was successfully destroyed." }
format.json { head :no_content }
end
end
private
def set_app_collection
#app_collection = app_collection.find(params[:id])
end
def app_collection_params
params.require(:app_collection).permit(:app_collection_type_id, :name, :company_id)
end
end
InvoicesController
class InvoicesController < ApplicationController
before_action :set_invoice, only: %i[ show edit update destroy ]
prepend_before_action :set_tenant
after_action :create_invoice_app_collection, only: [:create, :update]
def new
#invoice_app_collection = Invoice.new
end
def create
#invoice = Invoice.new(invoice_params)
respond_to do |format|
if #invoice.save
format.html { redirect_to invoice_url(#invoice), notice: "Invoice was successfully created." }
format.json { render :show, status: :created, location: #invoice }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #invoice.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #invoice.update(invoice_params)
format.html { redirect_to invoice_url(#invoice), notice: "Invoice was successfully updated." }
format.json { render :show, status: :ok, location: #invoice }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: #invoice.errors, status: :unprocessable_entity }
end
end
end
private
def set_invoice
#invoice = Invoice.find(params[:id])
end
def invoice_params
params.require(:invoice).permit(:company_id, :po_number, :amount, :expiration, {:app_collection_id => []} )
end
def create_invoice_app_collection
InvoiceAppCollection.create(
po_number: #invoice.po_number,
app_collection: #invoice.app_collection
)
end
end
InvoiceAppCollectionsController
class InvoiceAppCollectionsController < ApplicationController
before_action :set_invoice_app_collection, only: %i[ show edit update destroy ]
prepend_before_action :set_tenant
def new
#invoice_app_collection = InvoiceAppCollection.new
end
private
def set_invoice_app_collection
#invoice_app_collection = InvoiceAppCollection.find(params[:id])
end
def invoice_app_collection_params
params.require(:invoice_app_collection).permit(:company_id, :po_number, {:app_collection => []} )
end
end
App Collection being set in the invoice form
<div>
<%= form.label :app_collection, style: "display: block" %>
<label> Select multiple app collections by holding the command key </label>
<%= form.select :app_collection, options_for_select(app_collection.all.map {|a| [a.name, a.name]}),{include_blank: false} , class:"form-select", multiple: true %>
</div>
Schema
create_table "app_collections", charset: "latin1", force: :cascade do |t|
t.integer "app_collection_type_id"
t.string "name"
t.integer "company_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "invoice_app_collections", charset: "latin1", force: :cascade do |t|
t.integer "company_id"
t.string "po_number"
t.string "app_collection"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "invoices", charset: "latin1", force: :cascade do |t|
t.integer "company_id"
t.string "po_number"
t.decimal "amount", precision: 10
t.datetime "expiration"
t.string "app_collection"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
I believe that the issue is that the app_collection is an array that gets sent to InvoiceAppController so I set it to an array in both controllers and that hasn't fixed it. I also allowed InvoiceAppCollection to accept nested attribues for app_collection but that also isn't fixing it.
I'm not really sure how to resolve this error so any guidance would be very appreciated
Thank you!
I found a small problem, you wrote: #invoice.app_collection, but as your Invoice model is:
class Invoice < ApplicationRecord
has_many :app_collections, through: :invoice_app_collections
end
The code will look for relation belongs_to :app_collection, it required column app_collection_id in your Invoice model, which is not correct in this many-to-many between Invoice and AppCollection. Btw, I think this part {:app_collection_id => []} of invoice_params could raise error when this code Invoice.new(invoice_params) is executed
My suggestion, to update the many-to-many relation:
#invoice.app_collections = AppCollection.where(id: params[:app_collection_ids]) // maybe you will want to update the params structure
#invoice.save
This code will auto-generate correspondant InvoiceAppCollection records.

Undefined Method for Active Record

When creating a new job, I get an error about an undefined method Employee. I will post relevant sections of my code; thanks in advance for the help!
Here is the error message:
undefined method `employee' for #
ActiveRecord::Associations::CollectionProxy []
_form.html.erb (where error is occuring):
<td colspan="4">Client-Job
# <%= text_field_tag 'client_num', #job.opportunities.employee.office.client_num, :size => "4", :readonly => true, :tabindex => -1 %>
-<%= f.text_field :number %></td>
Jobs Controller:
class JobsController < ApplicationController
before_action :set_job, only: [:show, :edit, :update, :destroy]
skip_load_and_authorize_resource
# GET /jobs
# GET /jobs.json
def index
#jobs = Job.all
end
# GET /jobs/1
# GET /jobs/1.json
def show
end
# GET /jobs/new
def new
#job = Job.new
end
# GET /jobs/1/edit
def edit
end
# POST /jobs
# POST /jobs.json
def create
#job = Job.new(job_params)
respond_to do |format|
if #job.save
format.html { redirect_to #job, notice: 'Job was successfully created.' }
format.json { render :show, status: :created, location: #job }
else
format.html { render :new }
format.json { render json: #job.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /jobs/1
# PATCH/PUT /jobs/1.json
def update
respond_to do |format|
if #job.update(job_params)
format.html { redirect_to #job, notice: 'Job was successfully updated.' }
format.json { render :show, status: :ok, location: #job }
else
format.html { render :edit }
format.json { render json: #job.errors, status: :unprocessable_entity }
end
end
end
# DELETE /jobs/1
# DELETE /jobs/1.json
def destroy
#job.destroy
respond_to do |format|
format.html { redirect_to jobs_url, notice: 'Job was successfully deleted.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_job
#job = Job.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def job_params
params.require(:job).permit(:opportunity_id, :number, :name, :flight_date, :flight_sub, :camera, :roll, :map_type, :plan_only, :lab_only, :est_hrs_model, :due_date, :edge_job_id, :custom_trans, :comp_inhouse, :delivered_date, :done, :control_in, :control_status, :at_date, :control_results, :control_check, :scan_staff, :scan_date, :scan_check, :comp_staff, :comp_date, :comp_check, :comp_sub, :comp_sub_due_date, :comp_sub_rec, :img_staff, :img_date, :img_check, :edit_staff, :edit_date, :edit_check, :notes, :file1, :file2, :file3, :file4, :file5, :add_files)
end
end
Employee Controller:
class EmployeesController < ApplicationController
before_action :set_employee, only: :show
skip_load_and_authorize_resource
# GET /employees
# GET /employees.json
def index
#employees = Employee.all
end
# GET /employees/1
# GET /employees/1.json
def show
end
# GET /employees/new
def new
#employee = Employee.new
end
# GET /employees/1/edit
def edit
end
# POST /employees
# POST /employees.json
def create
#employee = Employee.new(employee_params)
respond_to do |format|
if #employee.save
format.html { redirect_to #employee, notice: 'Contact was successfully created.' }
format.json { render :show, status: :created, location: #employee }
else
format.html { render :new }
format.json { render json: #employee.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /employees/1
# PATCH/PUT /employees/1.json
def update
respond_to do |format|
if #employee.update(employee_params)
format.html { redirect_to #employee, notice: 'Contact was successfully updated.' }
format.json { render :show, status: :ok, location: #employee }
else
format.html { render :edit }
format.json { render json: #employee.errors, status: :unprocessable_entity }
end
end
end
# DELETE /employees/1
# DELETE /employees/1.json
def destroy
#employee.destroy
respond_to do |format|
format.html { redirect_to employees_url, notice: 'Contact was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_employee
#employee = Employee.find(params[:id])
#opportunities = #employee.opportunities.all
end
# Never trust parameters from the scary internet, only allow the white list through.
def employee_params
params.require(:employee).permit(:office_id, :f_name, :l_name, :suffix, :position, :email, :phone, :ext, :mobile, :per_email, :per_phone, :archived, :replacement)
end
end
Job Model:
class Job < ActiveRecord::Base
mount_uploader :file1, AttachmentUploader
belongs_to :cost_proposal
has_many :opportunities
end
Employee Model:
class Employee < ActiveRecord::Base
belongs_to :office
has_many :opportunities
has_one :user
delegate :company, to: :office
validates :f_name, :l_name, presence: true
def self.emp_id(emp_id)
find_by(id: emp_id)
end
def self.emp_f_name(emp_id)
find_by(id: emp_id).f_name
end
def name_1
[f_name, l_name].compact.join(' ')
end
def full_name
if suffix?
[name_1, suffix].compact.join(', ')
else
name_1
end
end
def self.emp_full_name(emp_id)
find_by(id: emp_id).full_name
end
def full_phone
if ext?
[phone, ext].compact.join(' ext: ')
else
phone
end
end
end
Schema.rb:(relevant tables)
create_table 'employees', force: true do |t|
t.integer 'office_id'
t.string 'f_name'
t.string 'l_name'
t.string 'suffix'
t.string 'email'
t.string 'phone'
t.string 'ext'
t.string 'mobile'
t.string 'per_email'
t.string 'per_phone'
t.integer 'archived'
t.integer 'replacement'
t.datetime 'created_at'
t.datetime 'updated_at'
t.string 'position'
end
create_table 'jobs', force: true do |t|
t.integer 'cost_proposal_id'
t.string 'number'
t.string 'name'
t.date 'flight_date'
t.string 'flight_sub'
t.string 'camera'
t.string 'roll'
t.string 'map_type'
t.integer 'plan_only'
t.integer 'lab_only'
t.integer 'est_hrs_model'
t.date 'due_date'
t.integer 'edge_job_id'
t.integer 'custom_trans'
t.integer 'comp_inhouse'
t.date 'delivered_date'
t.integer 'done'
t.date 'control_in'
t.string 'control_status'
t.date 'at_date'
t.string 'control_results'
t.integer 'control_check'
t.string 'scan_staff'
t.date 'scan_date'
t.integer 'scan_check'
t.string 'comp_staff'
t.date 'comp_date'
t.integer 'comp_check'
t.string 'comp_sub'
t.date 'comp_sub_due_date'
t.integer 'comp_sub_rec'
t.string 'img_staff'
t.date 'img_date'
t.integer 'img_check'
t.string 'edit_staff'
t.date 'edit_date'
t.integer 'edit_check'
t.text 'notes'
t.string 'file1'
t.string 'file2'
t.string 'file3'
t.string 'file4'
t.string 'file5'
t.string 'add_files'
t.datetime 'created_at'
t.datetime 'updated_at'
t.integer 'flown'
t.integer 'cust_trans'
t.integer 'delivered'
t.string 'at_staff'
t.integer 'at_check'
t.integer 'opportunity_id'
end
**Update:**Adding opportunity client model/schema
Opportunity Model:
class Opportunity < ActiveRecord::Base
belongs_to :employee
has_one :user
has_many :film_specs
has_many :digital_specs
has_many :film_quotes
has_many :cost_proposals
has_many :jobs
validates :opp_status_id, presence: true
end
Opportunity Schema:
create_table 'opportunities', force: true do |t|
t.integer 'employee_id'
t.integer 'emp2_id'
t.integer 'emp3_id'
t.string 'name'
t.datetime 'prop_date'
t.integer 'opp_status_id'
t.string 'delay'
t.date 'con_signed'
t.integer 'quote_won_id'
t.float 'total_cost'
t.date 'exp_close'
t.integer 'pri_comp_id'
t.text 'notes'
t.datetime 'created_at'
t.datetime 'updated_at'
t.string 'lost'
t.string 'won'
t.string 'location'
t.integer 'pm_id'
t.integer 'job_id'
end
Client Model:
class Company < ActiveRecord::Base
mount_uploader :logo, LogoUploader
has_many :offices
has_many :employees, through: :offices
has_one :office_type
validates :name, uniqueness: { message: 'That company already exists' }
def self.master_company
find_by(type_id: 1)
end
def self.company_name(comp_id)
find_by(id: comp_id).name
end
end
Client schema:
create_table 'companies', force: true do |t|
t.string 'name'
t.string 'website'
t.string 'logo'
t.datetime 'created_at'
t.datetime 'updated_at'
t.integer 'type_id'
end
Your issue is that you're calling .employee on an ActiveRecord collection (#job.opportunities). It looks like you're trying to display the client number using #job.opportunities.employee.office.client_num which will never work since you would first need to select a single opportunity record to get its employee. You should revisit how your Job and Office models are associated.

Rails 4 NoMethodError in Jobs#new

A little background, I took over a project that someone else started and hasn't worked on for 8ish months. The project is a CRM application built using Rails 4. I'm having a little trouble picking up where they left off, and am looking for help from seasoned Rails developers. The error I am receiving is when I try to add a new job from a job tracker page. The error I am receiving is:
ActionView::Template::Error (undefined method `opportunity' for #<Job:0x62d0240>):
1: <% #job[:opportunity_id] = params[:opportunity_id] %>
2: <% title "New #{#job.opportunity.name} Job"%>
3:
4: <%
5: #job[:name] = #job.opportunity.name
app/views/jobs/new.html.erb:2:in `_app_views_jobs_new_html_erb___882142983_51776136'
and the error is occuring on line 2 of the above. I will post relevant code, let me know if I need to add anything else. Thanks in advance!
Jobs new view (where error is occuring)
<% #job[:opportunity_id] = params[:opportunity_id] %>
<% title "New #{#job.opportunity.name} Job"%>
<%
#job[:name] = #job.opportunity.name
#pm = #job.opportunity.pm_id
%>
<br><br>
<%= render 'form' %>
Opportunity Controller
class OpportunitiesController < ApplicationController
before_action :set_opportunity, only: [:show, :edit, :update, :destroy]
load_and_authorize_resource
# GET /opportunities
# GET /opportunities.json
def index
#opportunities = Opportunity.all
end
# GET /opportunities/1
# GET /opportunities/1.json
def show
end
# GET /opportunities/new
def new
#opportunity = Opportunity.new
end
# GET /opportunities/1/edit
def edit
end
# POST /opportunities
# POST /opportunities.json
def create
#opportunity = Opportunity.new(opportunity_params)
respond_to do |format|
if #opportunity.save
format.html { redirect_to #opportunity, notice: 'Opportunity was successfully created.' }
format.json { render :show, status: :created, location: #opportunity }
else
format.html { render :new }
format.json { render json: #opportunity.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /opportunities/1
# PATCH/PUT /opportunities/1.json
def update
respond_to do |format|
if #opportunity.update(opportunity_params)
format.html { redirect_to #opportunity, notice: 'Opportunity was successfully updated.' }
format.json { render :show, status: :ok, location: #opportunity }
else
format.html { render :edit }
format.json { render json: #opportunity.errors, status: :unprocessable_entity }
end
end
end
# DELETE /opportunities/1
# DELETE /opportunities/1.json
def destroy
#opportunity.destroy
respond_to do |format|
format.html { redirect_to opportunities_url, notice: 'Opportunity was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_opportunity
#opportunity = Opportunity.find(params[:id])
#film_specs = #opportunity.film_specs.all
#digital_specs = #opportunity.digital_specs.all
end
# Never trust parameters from the scary internet, only allow the white list through.
def opportunity_params
params.require(:opportunity).permit(:employee_id, :emp2_id, :emp3_id, :name, :prop_date, :opp_status_id, :delay, :won, :lost, :con_signed, :quote_won_id, :total_cost, :exp_close, :pri_comp_id, :notes, :location, :pm_id)
end
end
Job Controller
class JobsController < ApplicationController
before_action :set_job, only: [:show, :edit, :update, :destroy]
skip_load_and_authorize_resource
# GET /jobs
# GET /jobs.json
def index
#jobs = Job.all
end
# GET /jobs/1
# GET /jobs/1.json
def show
end
# GET /jobs/new
def new
#job = Job.new do |j|
if params[:opportunity_id].present?
j.opportunity_id = params[:opportunity_id]
end
end
end
# GET /jobs/1/edit
def edit
end
# POST /jobs
# POST /jobs.json
def create
#job = Job.new(job_params)
respond_to do |format|
if #job.save
format.html { redirect_to #job, notice: 'Job was successfully created.' }
format.json { render :show, status: :created, location: #job }
else
format.html { render :new }
format.json { render json: #job.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /jobs/1
# PATCH/PUT /jobs/1.json
def update
respond_to do |format|
if #job.update(job_params)
format.html { redirect_to #job, notice: 'Job was successfully updated.' }
format.json { render :show, status: :ok, location: #job }
else
format.html { render :edit }
format.json { render json: #job.errors, status: :unprocessable_entity }
end
end
end
# DELETE /jobs/1
# DELETE /jobs/1.json
def destroy
#job.destroy
respond_to do |format|
format.html { redirect_to jobs_url, notice: 'Job was successfully deleted.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_job
#job = Job.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def job_params
params.require(:job).permit(:opportunity_id, :number, :name, :flight_date, :flight_sub, :camera, :roll, :map_type, :plan_only, :lab_only, :est_hrs_model, :due_date, :edge_job_id, :custom_trans, :comp_inhouse, :delivered_date, :done, :control_in, :control_status, :at_date, :control_results, :control_check, :scan_staff, :scan_date, :scan_check, :comp_staff, :comp_date, :comp_check, :comp_sub, :comp_sub_due_date, :comp_sub_rec, :img_staff, :img_date, :img_check, :edit_staff, :edit_date, :edit_check, :notes, :file1, :file2, :file3, :file4, :file5, :add_files)
end
end
Opportunity Model
class Opportunity < ActiveRecord::Base
belongs_to :employee
has_one :user
has_many :film_specs
has_many :digital_specs
has_many :film_quotes
has_many :cost_proposals
has_many :jobs
validates_presence_of :opp_status_id
end
Job Model
class Job < ActiveRecord::Base
mount_uploader :file1, AttachmentUploader
belongs_to :cost_proposal
has_many :opportunities
end
Job Schema
create_table "jobs", force: true do |t|
t.integer "cost_proposal_id"
t.string "number"
t.string "name"
t.date "flight_date"
t.string "flight_sub"
t.string "camera"
t.string "roll"
t.string "map_type"
t.integer "plan_only"
t.integer "lab_only"
t.integer "est_hrs_model"
t.date "due_date"
t.integer "edge_job_id"
t.integer "custom_trans"
t.integer "comp_inhouse"
t.date "delivered_date"
t.integer "done"
t.date "control_in"
t.string "control_status"
t.date "at_date"
t.string "control_results"
t.integer "control_check"
t.string "scan_staff"
t.date "scan_date"
t.integer "scan_check"
t.string "comp_staff"
t.date "comp_date"
t.integer "comp_check"
t.string "comp_sub"
t.date "comp_sub_due_date"
t.integer "comp_sub_rec"
t.string "img_staff"
t.date "img_date"
t.integer "img_check"
t.string "edit_staff"
t.date "edit_date"
t.integer "edit_check"
t.text "notes"
t.string "file1"
t.string "file2"
t.string "file3"
t.string "file4"
t.string "file5"
t.string "add_files"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "flown"
t.integer "cust_trans"
t.integer "delivered"
t.string "at_staff"
t.integer "at_check"
t.integer "opportunity_id"
end
Opportunity Schema
create_table "opportunities", force: true do |t|
t.integer "employee_id"
t.integer "emp2_id"
t.integer "emp3_id"
t.string "name"
t.datetime "prop_date"
t.integer "opp_status_id"
t.string "delay"
t.date "con_signed"
t.integer "quote_won_id"
t.float "total_cost"
t.date "exp_close"
t.integer "pri_comp_id"
t.text "notes"
t.datetime "created_at"
t.datetime "updated_at"
t.string "lost"
t.string "won"
t.string "location"
t.integer "pm_id"
t.integer "job_id"
end
You don't have an opportunity method because it's a has_many relation, so you have opportunities and is an array. But you have the opportunitity_id so you can find your opportunity object.
opportunity = Opportunity.find(params[:opportunity_id])

Article/post drafts in Rails

I am working on a wiki application in Rails that would be publicly editable. I have an articles controller and a drafts controller. When someone clicks 'edit' on an article, I would like to create a new draft with the contents of the original article, and then save that to the database table when the user clicks 'save'. Any ideas on how I might go about doing this? I've been stuck on it for a few days.
Currently, each article belongs_to a category, a subcategory, and has_many drafts.
Database schema:
ActiveRecord::Schema.define(version: 20160723153357) do
create_table "articles", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "title"
t.text "content"
t.integer "category_id"
t.integer "subcategory_id"
end
create_table "categories", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "drafts", force: :cascade do |t|
t.string "title"
t.text "content"
t.integer "category_id"
t.integer "subcategory_id"
t.integer "article_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "subcategories", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "category_id"
end
end
Articles_controller:
class ArticlesController < ApplicationController
before_action :set_article, only: [:show, :edit, :update, :destroy]
# GET /articles
# GET /articles.json
def index
if params[:category].blank? && params[:subcategory].blank?
#articles = Article.all.order("created_at DESC")
elsif params[:subcategory].blank?
#category_id = Category.find_by(name: params[:category]).id
#articles = Article.where(category_id: #category_id).order("created_at DESC")
else
#subcategory_id = Subcategory.find_by(name: params[:subcategory]).id
#articles = Article.where(subcategory_id: #subcategory_id).order("created_at DESC")
end
end
# GET /articles/1
# GET /articles/1.json
def show
end
# GET /articles/new
def new
#article = Article.new
end
# GET /articles/1/edit
def edit
end
# POST /articles
# POST /articles.json
def create
#parameters = article_params
#parameters[:category] = Category.find_by(id: Subcategory.find_by(id: article_params[:subcategory_id]).category_id)
#article = Article.new(#parameters)
respond_to do |format|
if #article.save
format.html { redirect_to #article, notice: 'Article was successfully created.' }
format.json { render :show, status: :created, location: #article }
else
format.html { render :new }
format.json { render json: #article.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /articles/1
# PATCH/PUT /articles/1.json
def update
respond_to do |format|
if #article.update(article_params)
format.html { redirect_to #article, notice: 'Article was successfully updated.' }
format.json { render :show, status: :ok, location: #article }
else
format.html { render :edit }
format.json { render json: #article.errors, status: :unprocessable_entity }
end
end
end
# DELETE /articles/1
# DELETE /articles/1.json
def destroy
#article.destroy
respond_to do |format|
format.html { redirect_to articles_url, notice: 'Article was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_article
#article = Article.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def article_params
params.require(:article).permit(:title,:content,:subcategory_id)
end
end
Drafts_controller:
class DraftsController < ApplicationController
before_action :set_draft, only: [:show, :edit, :update, :destroy]
# GET /drafts
# GET /drafts.json
def index
#drafts = Draft.all
end
# GET /drafts/1
# GET /drafts/1.json
def show
end
# GET /drafts/new
def new
#draft = Draft.new
end
# GET /drafts/1/edit
def edit
end
# POST /drafts
# POST /drafts.json
def create
#parameters = draft_params
#parameters[:article_id] = params[:article_id]
#parameters[:subcategory_id] = 2
#parameters[:category_id] = 2
#draft = Draft.new(#parameters)
respond_to do |format|
if #draft.save
format.html { redirect_to #draft, notice: 'Draft was successfully created.' }
format.json { render :show, status: :created, location: #draft }
else
format.html { render :new }
format.json { render json: #draft.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /drafts/1
# PATCH/PUT /drafts/1.json
def update
respond_to do |format|
if #draft.update(draft_params)
format.html { redirect_to #draft, notice: 'Draft was successfully updated.' }
format.json { render :show, status: :ok, location: #draft }
else
format.html { render :edit }
format.json { render json: #draft.errors, status: :unprocessable_entity }
end
end
end
# DELETE /drafts/1
# DELETE /drafts/1.json
def destroy
#draft.destroy
respond_to do |format|
format.html { redirect_to drafts_url, notice: 'Draft was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_draft
#draft = Draft.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def draft_params
params.require(:draft).permit(:title, :content)
end
end
Article model:
class Article < ApplicationRecord
belongs_to :category
belongs_to :subcategory
has_many :drafts
end
Draft model:
class Draft < ApplicationRecord
belongs_to :category
belongs_to :subcategory
belongs_to :article
end
I think an approach I would probably follow would be to extract the content information to another table altogether. Here's a rough implementation I could come up with immediately:
class Article < ApplicationRecord
#column_names: ['type:string']
has_many :contents
has_one :current_content, -> { current.or(approved) }, class_name: 'Content'
delegate :title, :content, to: :current_content, allow_nil: true
end
class Content < ApplicationRecord
#column_names: ["article_id:int", "title:string", "content:text", "status:int"]
belongs_to :article
enum status: [:unapproved, :approved, :current]
end
class Draft < Article
#use STI here
end
#services/set_current_article_content.rb
class SetCurrentArticleContent
attr_reader :article, :content
def initialize(article, content)
#article = article
#content = content
end
def call
article.current_content.approved!
content.current!
end
end
#services/edit_wiki_content.rb
class EditWikiContent.rb
attr_reader :article, :content
def initialize(article, content)
#article = article
#content = content
end
def call
article.contents << content
content.save!
end
end
#services/publish_draft.rb
class PublishDraft
attr_reader :draft
def initialize(draft)
#draft = draft
end
def call
draft.becomes!(Article)
end
end
There are three services which would handle the updating and setting of the current content and also publishing the draft, you could add some additional logic in any of them. Also note the condition for the current_content in the article model, your logic might be different from the way I have implemented it.

Categories stopped saving after creating a Join table in rails

This is my first time creating a Join table and I am a bit stuck. I have two tables: Categories and Products. I originally had it set up where Products belong to on category and Categories had many products. I just created a join table and changed my associations to has_and_belongs_to_many.
I have a form where multiple categories can be selected for a product but the categories selected are not saving in the database anymore.
In my controller I have created an array for category_id in my product params and I am wondering if there is something in my database that needs to be updated as well? Should I change categroy_id in database?
Here are my tables:
create_table "categories_products", id: false, force: :cascade do |t|
t.integer "category_id", null: false
t.integer "product_id", null: false
end
create_table "categories", force: :cascade do |t|
t.string "name"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "product_id"
t.integer "category_id"
end
create_table "products", force: :cascade do |t|
t.string "title"
t.text "description"
t.string "image_url"
t.integer "price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "image", default: "{}"
t.integer "category_id"
t.integer "product_id"
end
Here are my model associations:
class Product < ActiveRecord::Base
has_and_belongs_to_many :categories, :join_table => :categories_products
class Category < ActiveRecord::Base
has_and_belongs_to_many :products, :join_table => :categories_products
the categories selector in my new product form:
<div class="field">
<%= f.label :category_ids %><br>
<%= f.select :category_ids, Category.all.collect {|x| [x.name, x.id]}, {}, :multiple => true %>
</div>
Products controller:
class ProductsController < ApplicationController
before_filter :authenticate_admin!, :except => [:index, :show, :earings]
before_action :set_product, only: [:show, :edit, :update, :destroy]
# GET /products
# GET /products.json
def index
#products = Product.all
respond_to do |format|
format.html # index.html.erb
format.js # index.js.erb
format.json { render json: #products }
end
end
def show
end
def new
#products = Product.new
#categories = Category.order(:name)
end
# GET /products/1/edit
def edit
#categories = Category.order(:name)
end
# POST /products
# POST /products.json
def create
#products = Product.new(product_params)
respond_to do |format|
if #product.save
format.html { redirect_to #product, notice: 'Product was successfully created.' }
format.json { render :show, status: :created, location: #product }
else
format.html { render :new }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /products/1
# PATCH/PUT /products/1.json
def update
respond_to do |format|
if #product.update(product_params)
format.html { redirect_to #product, notice: 'Product was successfully updated.' }
format.json { render :show, status: :ok, location: #product }
else
format.html { render :edit }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
# DELETE /products/1
# DELETE /products/1.json
def destroy
#product.destroy
respond_to do |format|
format.html { redirect_to products_url, notice: 'Product was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_product
#product = Product.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def product_params
params.require(:product).permit(:title, :description, :image, :price, :category_ids => [])
end
def search_params
default_params = {}
default_params.merge({user_id_eq: current_user.id}) if signed_in?
# more logic here
params[:q].merge(default_params)
end
end

Resources