Ruby on Rails ActiveResource not saving resource model properly - ruby-on-rails

ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux],
Rails 4.2.5
I have two projects. from 1st project i am getting data into second project through api.
User model in 1st project:
class User < ActiveRecord::Base
has_many :cars
end
Car model in 1st project:
class Car < ActiveRecord::Base
belongs_to :user
end
Car model(remote) in 2nd project:
class Car < ActiveResource::Base
self.site = 'https://myeasyb-vssram.c9users.io'
self.format = :json
end
Gpstablecontroller(2nd project):
class GpstablesController < ApplicationController
before_action :set_gpstable, only: [:show, :edit, :update, :destroy]
# GET /gpstables
# GET /gpstables.json
def index
#gpstables = Gpstable.all
end
# GET /gpstables/1
# GET /gpstables/1.json
def show
end
# GET /gpstables/new
def new
#gpstable = Gpstable.new
#gpstables = Gpstable.all
end
# GET /gpstables/1/edit
def edit
#gpstables = Gpstable.all
end
# POST /gpstables
# POST /gpstables.json
def create
#cars = Car.all
#gpstable = Gpstable.new(gpstable_params)
#cars.each do |car|
if #gpstable.car_id == car.id
#car = car
end
end
#car.update_attribute(:gpss, #gpstable.device_id)
respond_to do |format|
if #gpstable.save
format.html { redirect_to gpstables_url, notice: 'Gpstable was successfully created.' }
format.json { render :show, status: :created, location: #gpstable }
else
format.html { render :new }
format.json { render json: #gpstable.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /gpstables/1
# PATCH/PUT /gpstables/1.json
def update
respond_to do |format|
if #gpstable.update(gpstable_params)
Car.all.each do |car|
if #gpstable.car_id == car.id.to_json
#car = car
end
if #gpstable.device_id == car.gpss
car.gpss = 0
car.save!
end
end
#car.gpss = #gpstable.device_id
#car.save!
format.html { redirect_to #gpstable, notice: 'Gpstable was successfully updated.' }
format.json { render :show, status: :ok, location: #gpstable }
else
format.html { render :edit }
format.json { render json: #gpstable.errors, status: :unprocessable_entity }
end
end
end
# DELETE /gpstables/1
# DELETE /gpstables/1.json
def destroy
#cars.each do |car|
if #gpstable.device_id == car.gpss
car.gpss = 0
car.user_id = #gpstable.user_id
car.save
end
end
#gpstable.destroy
respond_to do |format|
format.html { redirect_to gpstables_url, notice: 'Gpstable was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_gpstable
#gpstable = Gpstable.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def gpstable_params
params.require(:gpstable).permit(:device_id, :car_id, :user_id)
end
end
when creating gpstable record i want to update Gpss attribute of car model(remote, calling through api).
it is updating gpss attribute.But it is changing all foriegnkeys including user_id attribute of car model to null.
using devise for users in 1st project.

The problem is i am giving user_id to current user_id in car_params. so i was unable to edit this through resource model. so i changed this to create action.
In my first app i have car controller:
def car_params
params.require(:car).permit(:name, :model, :colour, :ac, :gpss, :wifi, :luggage, :cfare, :card, :crfare, :no, :nos, :user_id, {carpicss: []} ).**merge(user: :current_user)**
end
i removed .merge(user: :current_user) from above code.
and added this in create action
def create
#car = Car.new(car_params)
#car.card=" #{#car.name} : #{#car.no}"
#car.user_id=current_user.id #added here to save current user_id
respond_to do |format|
if #car.save
format.html { redirect_to cars_path, notice: 'Car was successfully created.' }
format.json { render :show, status: :created, location: cars_path }
else
format.html { render :new }
format.json { render json: #car.errors, status: :unprocessable_entity }
end
#car.reload
end
end

Related

One to Many To Many: One user has many store. One store has many products

I'm learning ROR. Trying to build this model: one user can have many store each store can have many product. I've been able to create store linking to its owner but I'm stuck at doing the same for product.
store.rb
class Store < ApplicationRecord
belongs_to :user
has_many :products, :foreign_key => :store_id
end
product.rb
class Product < ApplicationRecord
belongs_to :store
end
products_controller.rb
class ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :destroy]
# GET /products
# GET /products.json
def index
#products = Product.all
end
# GET /products/1
# GET /products/1.json
def show
end
# GET /products/new
def new
end
# GET /products/1/edit
def edit
end
# POST /products
# POST /products.json
def create
#product = 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(:product_name, :product_price, :product_description, :product_tag, :sku_code)
end
end
stores_controller.rb
class StoresController < ApplicationController
before_action :set_store, only: [:show, :edit, :update, :destroy]
# GET /stores
# GET /stores.json
def index
#stores = Store.all
end
# GET /stores/1
# GET /stores/1.json
def show
#products = Product.all
end
# GET /stores/new
def new
#store = Store.new
end
# GET /stores/1/edit
def edit
end
# POST /stores
# POST /stores.json
def create
#store = Store.new(store_params)
#store.user_id = current_user.id
respond_to do |format|
if #store.save
format.html { redirect_to #store, notice: 'Store was successfully created.' }
format.json { render :show, status: :created, location: #store }
else
format.html { render :new }
format.json { render json: #store.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /stores/1
# PATCH/PUT /stores/1.json
def update
respond_to do |format|
if #store.update(store_params)
format.html { redirect_to #store, notice: 'Store was successfully updated.' }
format.json { render :show, status: :ok, location: #store }
else
format.html { render :edit }
format.json { render json: #store.errors, status: :unprocessable_entity }
end
end
end
# DELETE /stores/1
# DELETE /stores/1.json
def destroy
#store.destroy
respond_to do |format|
format.html { redirect_to stores_url, notice: 'Store was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_store
#store = Store.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def store_params
params.require(:store).permit(:store_name, :store_description)
end
end
I expect when creating a product, it will get the store_id immediately. I'm keep getting "store must exist" message
From Rails 5, belongs_to requires the association object to be present. If your product object does not have a valid store_id (nil or inexistent store object), that product object will not be valid.
You can bypass this by allowing the association to be optional
class Product < ApplicationRecord
belongs_to :store, optional: true
end
Or, you should allow store_id as permitted parameter in your products_controller and pass it when you create a new product
# below code I assume that your store table has a column called 'store_name'
<%= form_for #product do |f| %>
<%= f.collection_select :store_id, current_user.stores, :id, :store_name, prompt: 'Please select the store of this product' %>
<%= f.submit %>
<% end %>

Rails 5.1 Trying to pass an attribute to a form using a link

I am trying to pass an attribute to an object that is being created by a link. I am on the show view of another object and I want to have two links available one that will make the :attribute false and the other to make the :attribute true. I have it set up so the default value of the this attribute is false and I tried using something like below, but it just saves it as nil in the database:
<%= link_to "Yes", new_building_listing_appointment_rented_unit_path(#building, #listing, #appointment, #rented_unit, leased: true) %>>
controller
class RentedUnitsController < ApplicationController
before_action :building
before_action :listing
before_action :appointment
before_action :set_rented_unit, only: [:show, :edit, :update, :destroy]
# GET /rented_units
# GET /rented_units.json
def index
#rented_units = appointment.rented_units
end
# GET /rented_units/1
# GET /rented_units/1.json
def show
end
# GET /rented_units/new
def new
#rented_unit = appointment.rented_units.new
end
# GET /rented_units/1/edit
def edit
end
# POST /rented_units
# POST /rented_units.json
def create
#rented_unit = appointment.rented_units.new(rented_unit_params)
respond_to do |format|
if #rented_unit.save
format.html { redirect_to [building, listing, appointment, #rented_unit], notice: 'Rented unit was successfully created.' }
format.json { render :show, status: :created, location: #rented_unit }
else
format.html { render :new }
format.json { render json: #rented_unit.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /rented_units/1
# PATCH/PUT /rented_units/1.json
def update
respond_to do |format|
if #rented_unit.update(rented_unit_params)
format.html { redirect_to [building, listing, appointment, #rented_unit], notice: 'Rented unit was successfully updated.' }
format.json { render :show, status: :ok, location: #rented_unit }
else
format.html { render :edit }
format.json { render json: #rented_unit.errors, status: :unprocessable_entity }
end
end
end
# DELETE /rented_units/1
# DELETE /rented_units/1.json
def destroy
#rented_unit.destroy
respond_to do |format|
format.html { redirect_to building_listing_appointment_rented_units_path(#building, #listing, #appointment), notice: 'Rented unit was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_rented_unit
#rented_unit = appointment.rented_units.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def rented_unit_params
params.require(:rented_unit).permit(:unit_no, :unit_model, :price, :bedrooms, :bathrooms, :half_baths, :square_footage, :leased, :appointment_id)
end
def building
#building ||= Building.find(params[:building_id])
end
def listing
#listing ||= Listing.find(params[:listing_id])
end
def appointment
#appointment ||= Appointment.find(params[:appointment_id])
end
end
From what I understand you are looking to populate leased attribute auto when you open a new from from the link.
You need to give the param param to the link.
<%= link_to "Yes", new_building_listing_appointment_rented_unit_path(#building, #listing, #appointment, #rented_unit, rented_unit: { leased: true } ) %>>
In the controller then you can do some thing like
# GET /rented_units/new
def new
#rented_unit = appointment.rented_units.new(rented_unit_params)
end
Then, in the new form you will see the checkbox (or other control) selected.

Rails generate records for secondary model on create

I am making a sort of checklist section for my site. I have a model called commission that will contain data about a commissioning task. What I need to do is when a new commission entry is created I need to create a series of about 30 commission tasks that will link to it. A sort of checklist of predefined values for a person to go down through and check. What would be the best way to do this?
Here are my models and controller:
commission.rb
class Commission < ApplicationRecord
has_many :comtasks
belongs_to :project
belongs_to :user
accepts_nested_attributes_for :comtasks, allow_destroy: true
end
comtask.rb
class Comtask < ApplicationRecord
belongs_to :commission
belongs_to :user
end
commissions_controller.rb
class CommissionsController < ApplicationController
before_action :set_commission, only: [:show, :edit, :update, :destroy]
# GET /commissions
# GET /commissions.json
def index
#commissions = Commission.all
end
# GET /commissions/1
# GET /commissions/1.json
def show
end
# GET /commissions/new
def new
#commission = Commission.new
end
# GET /commissions/1/edit
def edit
end
# POST /commissions
# POST /commissions.json
def create
#commission = Commission.new(commission_params)
respond_to do |format|
if #commission.save
format.html { redirect_to #commission, notice: 'Commission was successfully created.' }
format.json { render :show, status: :created, location: #commission }
else
format.html { render :new }
format.json { render json: #commission.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /commissions/1
# PATCH/PUT /commissions/1.json
def update
respond_to do |format|
if #commission.update(commission_params)
format.html { redirect_to #commission, notice: 'Commission was successfully updated.' }
format.json { render :show, status: :ok, location: #commission }
else
format.html { render :edit }
format.json { render json: #commission.errors, status: :unprocessable_entity }
end
end
end
# DELETE /commissions/1
# DELETE /commissions/1.json
def destroy
#commission.destroy
respond_to do |format|
format.html { redirect_to commissions_url, notice: 'Commission was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_commission
#commission = Commission.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def commission_params
params.require(:commission).permit(:project_id, :user_id, :description, :objectname, :location, comtasks_attributes: [:id, :content, :notes])
end
end
Any thoughts or suggestions are appreciated.
below is the idea,
def create
#commission = Commission.create!(commission_params)
# use create not new to generate #commission.id value
# so comtask records can use the id value as reference
create_comtasks_job
# for comtask create I put in other method
respond_to do |format|
if #commission.save
format.html { redirect_to #commission, notice: 'Commission was successfully created.' }
format.json { render :show, status: :created, location: #commission }
else
format.html { render :new }
format.json { render json: #commission.errors, status: :unprocessable_entity }
end
end
end
def create_comtasks_job
# loop 30 tasks / or manual as follow
#commission.comtasks.build(content: 'content1',notes:'notes1')
#commission.comtasks.build(content: 'content2',notes:'notes2')
end
additional code for your model
make sure for your model has relation like sample below
for your model
class Commission < ActiveRecord::Base
has_many :comtasks
end
class Comtask < ActiveRecord::Base
belongs_to :commission
end

Merit doesn't add points to user after create action

I've used this instructions for simply add score when a user creates a "solucion" (which is a kind of "answer" to a micropost). I have added the has_merit line to user.rb (user model).
I want to display the user points earned for that action at the show view.
show.html.erb (for solucion):
<h2><span class="red"><%= current_user.points %></span><br>Points</br></h2>
It displays 0 points...
point_rules.rb:
module Merit
class PointRules
include Merit::PointRulesMethods
def initialize
score 5, on: 'solucions#create'
end
end
end
When I create a solucion with the current_user (already saving the user_id index and identifier to solucion), This is what my rails server output shows...
Direct link to github gist:
https://gist.github.com/roadev/7b34fd67ab93c979fa48
Embed:
<script src="https://gist.github.com/roadev/7b34fd67ab93c979fa48.js"></script>
EDIT:
solucions_micropost.rb
class SolucionsController < ApplicationController
before_action :set_solucion, only: [:show, :edit, :update, :destroy]
def index
#solucions = Solucion.all
end
def show
end
def new
#solucion = current_user.solucions.build
end
def edit
end
def create
#solucion = current_user.solucions.build(solucion_params)
respond_to do |format|
if #solucion.save
format.html { redirect_to #solucion, notice: 'Solucion was successfully created.' }
format.json { render action: 'show', status: :created, location: #solucion }
else
format.html { render action: 'new' }
format.json { render json: #solucion.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #solucion.update(solucion_params)
format.html { redirect_to #solucion, notice: 'Solucion was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #solucion.errors, status: :unprocessable_entity }
end
end
end
def destroy
#solucion.destroy
respond_to do |format|
format.html { redirect_to solucions_url }
format.json { head :no_content }
end
end
private
def set_solucion
#solucion = Solucion.find(params[:id])
end
def current_micropost
#solucion = microposts.find_by(id: params[:id])
end
def solucion_params
params.require(:solucion).permit(:solucion, :image, :micropost_id)
end
end
user.rb:
class User < ActiveRecord::Base
has_many :dreams
has_many :microposts
has_many :solucions
has_merit
end
I had a problem with a migration when I installed the merit gem.

how do I write create method in the controller for a submission form that uses a join table?

I'm trying to create a form that allow called submits. I've got all the appropriate MVC created. I've then created a model called questions that works and am using active admin to allow admin users to add new questions to the form as they see fit. When I test submitting the form I get this error
undefined method `each' for nil:NilClass
#submit = Submit.new(submit_params)
#submit.save
params[:submit][:question_ids].each do |question_id|
#question = Question.find(question_id)
#submit.questions << #question
end
Here's my submits controller:
class SubmitsController < ApplicationController
before_action :set_submit, only: [:show, :edit, :update, :destroy]
def index
#submits = Submit.all
end
def show
end
def new
#submit = Submit.new
#questions = Question.all
end
def edit
end
def create
#submit = Submit.new(submit_params)
#submit.save
params[:submit][:question_ids].each do |question_id|
#question = Question.find(question_id)
#submit.questions << #question
end
respond_to do |format|
if #submit.save
format.html { redirect_to #submit, notice: 'Application was successfully created.' }
format.json { render :show, status: :created, location: #submit }
else
format.html { render :new }
format.json { render json: #submit.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #submit.update(submit_params)
format.html { redirect_to #submit, notice: 'Application was successfully updated.' }
format.json { render :show, status: :ok, location: #submit }
else
format.html { render :edit }
format.json { render json: #submit.errors, status: :unprocessable_entity }
end
end
end
def destroy
#submit.destroy
respond_to do |format|
format.html { redirect_to submits_url, notice: 'Submit was successfully destroyed.' }
format.json { head :no_content }
end
end
Here's my Submit and Question model:
Submit:
class Submit < ActiveRecord::Base
has_and_belongs_to_many :questions
belongs_to :user
end
Question:
class Question < ActiveRecord::Base
has_and_belongs_to_many :submits
end
I'm sure it's some kind of syntax error in my controller but I don't know what. Still pretty new to using join tables. Any help/explanation would be very appreciated.
Thanks!
You don't need this
params[:submit][:question_ids].each do |question_id|
#question = Question.find(question_id)
#submit.questions << #question
end
I don't see your submit params but if you add question ids to the permitted parameters then rails will build the entry in the join table on it's own.
def submit_params
params.require(:submit).permit(:user_id, question_ids: [])
end

Resources