Ruby on rails: Creating a model entry with a belongs_to association
Just call create
on the jobs
collection of the client:
c = Client.find(1)
c.jobs.create(:subject => "Test", :description => "This is a test")
Rails - Creating a belongs_to association between models prevents me from editing the model
Use:
belongs_to :moderator, class_name: "User", optional: true
In rails 5, belongs_to
enforces existence of the associated record by default. You need to use optional: true
in order to allow moderator_id to be nil.
Rails 5: Creating an object with a belongs_to association that belongs_to user
Although there is probably a more standard use case sort of answer, the following worked for me.
I created a new column in the user table to store an integer in active_project to reference the project's id. When making a doc, I first set @project to the project with the id of current_user.active_project, then create the doc as belonging to the @project.
This may be a little backwards, but it works, and I can use the active_project data to allow users to revisit their last project open login. Thanks @pavan for the suggestions, they set me down the right path! :)
Rails when creating record, inserting belongs_to association
in rails way you can use the build_association method refer doc. Also the association should be created only when parent object is created so use after_create
callback
class Character < ActiveRecord::Base
has_one :character_stats
after_create :create_stats
def create_stats
state = self.build_character_stats({}) # empty hash as you are not passing any attributes
state.save
end
end
Also, the model name CharacterStats looks plural and that can violate the naming convention and can cause some issue like resolving association class on run time and so.
Force create a record with a belongs_to association
To be clear, yes this is possible.
Associations in your models are only there to set foreign keys
in your datatables. As such, if you wanted to create a Job
(although it belongs_to :user
), you'd be able to set all the attributes you desired, and then update :user_id
later.
Here's a good reference:
This shows the datatable structure for the typical belongs_to
/ has_many
association. Whilst to associate the two objects, you need to have the correct foreign_key
, you can populate them as you wish.
Rails: How to create a new record in a belongs_to + has_many relationship with both ends validating the presence of each other?
can u try something like this?
game = Game.new
manufacturer = Manufacturer.new(games: [game])
manufacturer.save
and turn on
class Manufacturer < ActiveRecord::Base
has_many :games, autosave: true
# etc etc
end
CRUD method for a model that belongs_to many models Rails
As @Anthony noted, you'll need to make your belongs_to
associations optional:
# app/models/contact.rb
class Contact < ApplicationRecord
belongs_to :branch, optional: true
belongs_to :division, optional: true
end
But another problem is that params[:division_id]
and params[:branch_id]
are always nil. Both of those keys exist inside the [:contact]
key. So the error you are getting should be ActiveRecord::RecordNotFound: Couldn't find Division with 'id'=
All that conditional logic is unnecessary. You can just make a new contact with whatever params are given. Also, you should be using Ruby convention for variable naming, which is snake_case instead of camelCase.
Finally, I assume you'll want to redirect HTML requests to either the branch or the division show page, depending on which was associated. So I've added logic to do that.
Here's a quick refactoring of the controller #create
action:
def create
@new_contact = Contact.new(contact_params)
if @new_contact.save
branch = @new_contact.branch
division = @new_contact.division
redirect_path = branch ? branch_path(branch) : division_path(division)
respond_to do |format|
format.js
format.html { redirect_to redirect_path, :notice => 'Contact created successfully!' }
format.json { render json: @new_contact, status: :created, location: @new_contact }
end
else
respond_to do |format|
format.html { render action: "new" }
format.json { render json: @new_contact, status: :unprocessable_entity }
end
end
end
This proves that it works:
# spec/controllers/contacts_controller_spec.rb
require 'rails_helper'
RSpec.describe ContactsController, type: :controller do
let(:company) { Company.create!(name: 'Company Name') }
let(:division) { Division.create!(name: 'Division Name', company: company) }
let(:branch) { Branch.create!(name: 'Branch Name', company: company) }
describe '#create' do
context 'when created with a division id' do
let(:attributes) { {'division_id' => division.id, 'name' => 'Contact Name'} }
it 'creates a contact record and associates it with the division' do
expect(Contact.count).to eq(0)
post :create, params: {contact: attributes}
expect(Contact.count).to eq(1)
contact = Contact.first
expect(contact.division).to eq(division)
end
end
context 'when created with a branch id' do
let(:attributes) { {'branch_id' => branch.id, 'name' => 'Contact Name'} }
it 'creates a contact record and associates it with the branch' do
expect(Contact.count).to eq(0)
post :create, params: {contact: attributes}
expect(Contact.count).to eq(1)
contact = Contact.first
expect(contact.branch).to eq(branch)
end
end
end
end
Related Topics
Dynamically Create a Class Inherited from Activerecord
Ruby - Return Byte Array Containing Two's Complement Representation of Bignum/Fixnum
Ruby 'Require' Call Fails on Custom Code
Should I Be Using Rails or Ruby for This Website Application? How
How Do to Print Two Zero's 00 as an Integer
Devise Omniauthable Breaks Omniauth Authentication with 'Could Not Find a Valid Mapping for Path'
Array#Rotate Equivalent in Ruby 1.8.7
Get Instance Variable Name from Itself in Ruby
Rake Aborted! Undefined Method 'Migration_Error=' for Activerecord::Base:Class
Ruby on Rails How to Deal with Nan
Validate Japanese Character in Active Record Callback
Error:'Incompatible Library Version' SQLite3-1.3.11 in Rails
Nesting Too Deep' Error While Retrieving JSON Using Httparty
Read and Write File Atomically
Prawn PDF: I Need to Generate Nested Tables
How to Specify a Struct as the Return Value of a Function in Rubyffi