I'm working on my spree rails app, and for some reasons I'm making some custom methods. I've created a new and create methods in the ProductsController, but the last one is not working propperly, it doesn't save the data in my DB and I cant realize why.
This is my controller:
module Spree
class ProductsController < Spree::StoreController
before_action :load_product, only: :show
before_action :load_taxon, only: :index
rescue_from ActiveRecord::RecordNotFound, :with => :render_404
helper 'spree/taxons'
respond_to :html
def index
#searcher = build_searcher(params.merge(include_images: true))
#products = #searcher.retrieve_products
#taxonomies = Spree::Taxonomy.includes(root: :children)
end
#########################################by_cjdc#############################################################
def newproduct
#product = Product.new();
#render '/spree/home/newproduct'
end
def createproduct
#name = params[:product][:name];
#description = params[:product][:description];
#product = Product.new({
:id => 4,
:name => #name,
:description => #description});
#product.save();
if #product.save()
redirect_to "/tutienda", :notice => "El producto ha sido insertado";
else
render '/spree/products/newproduct'
end
end
######################################################################################################
def show
#variants = #product.variants_including_master.active(current_currency).includes([:option_values, :images])
#product_properties = #product.product_properties.includes(:property)
#taxon = Spree::Taxon.find(params[:taxon_id]) if params[:taxon_id]
end
private
def accurate_title
if #product
#product.meta_title.blank? ? #product.name : #product.meta_title
else
super
end
end
def load_product
if try_spree_current_user.try(:has_spree_role?, "admin")
#products = Product.with_deleted
else
#products = Product.active(current_currency)
end
#product = #products.friendly.find(params[:id])
end
def load_taxon
#taxon = Spree::Taxon.find(params[:taxon]) if params[:taxon].present?
end
end
end
And my methods are newproduct and createproduct. I even tried whitn and abort before #product.save to see whats in the object, and the object have the data but then the DB doesn't get it. (sorry for my bad english).
First thing you really don't need ; after every line, ror doesn't require that.
Another thing if data isn't getting save to DB then you should make sure that is there any validation failing. Now how to check which validation isn't allowing to save. To know that use bang method with save.
save -> save!
! bang method will throw an exception if any validation is getting failed.
Then just check the error and fix it.
Related
I'd like to ask why i'm always getting nil value when running rspec controller test ?
I already read in this site and most of answers because plurals word using inside assigns
but in my case thats not working and i still got the same value
This is my Controller
class ContactsController < ApplicationController
load_and_authorize_resource
before_action :find_contact, only: [:show,:edit,:update,:destroy]
def index
authorize! :index, Contact
#contact = Contact.accessible_by(current_ability)
# #contact = Contact.all
end
def show
end
def new
#contact = Contact.new
end
def edit
end
def create
#contact = current_user.contact.new(contact_params)
if #contact.save
redirect_to #contact
else
render 'new'
end
end
def update
# #contact = Contact.find(params[:id])
if #contact.update(contact_params)
redirect_to #contact
else
render 'edit'
end
end
def destroy
#contact.destroy
redirect_to contacts_path
end
private
def contact_params
params.require(:contact).permit(:firstname,
:lastname,
:alamat,
details_attributes: [:id, :number, :_destroy])
end
def find_contact
#contact = Contact.find(params[:id])
end
end
And this is my simple controller test
require 'rails_helper'
RSpec.describe ContactsController do
describe "Contact" do
it "succesfully create the contact" do
contact = FactoryGirl.create(:contact)
get :index
# byebug
expect(assigns(:contacts)).to eq([contact])
end
end
end
Even i change assigns(:contacts) to assigns(:contact) i still got the same value. So where is that i am do wrong ?
Please kindly answer this, big thanks
Even i change assigns(:contacts) to assigns(:contact) i still got the
same value. So where is that i am do wrong ?
assigns and assert_template have been remove and extracted to a gem in Rails 5.
Source
You have an authorization check
authorize! :index, Contact
before the assignment to #contact.
But your test has no setup in order to grant permissions to the requesting user in any way.
It probably makes sense to have an additional test alongside the one you show in order to spot errors like this. E.g:
it "returns 200 (OK)" do
get :index
expect(response.response_code).to eq(200)
end
I have a model called Thing and a controller called Things.
I followed this tutorial to try and set a maximum amount of Things a user can create.
Here's the warning: the terminal is giving a warning (not a huge issue) of DEPRECATION WARNING: Passing an argument to force an association to reload is now deprecated and will be removed in Rails 5.1. Please call "reload" on the result collection proxy instead. What should I do to make it go away?
Here's the problem: The line self.errors.add(:base, "Exceeded Things Limit") isn't displaying an alert or notice in the view. How would I achieve this? It's not creating a new Thing (because I met the maximum limit of 2) which is good, but it's just reloading a new form which would be horrible for user experience.
I'm working Rails 5 and Devise.
Here's my Thing model:
class Thing < ApplicationRecord
belongs_to :user
validate :thing_count_within_limit, :on => :create
attr_accessor :validation_code, :flash_notice
def self.search(search)
if search
where("zipcode LIKE ?", "%#{search}%")
else
all
end
end
def thing_count_within_limit
if self.user.things(:reload).count >= 2
self.errors.add(:base, "Exceeded Things Limit")
end
end
end
And here's my Things controller:
class thingsController < ApplicationController
before_action :find_thing, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user_first, only: [:edit, :update, :destroy]
before_action :authorized_pilot, only: [:edit, :update, :destroy, :profile]
def index
#things = Thing.all.order("created_at ASC")
#things = Thing.search(params[:search])
end
def new
#thing = current_user.things.build
end
def create
#thing = current_user.things.build(thing_params)
if #thing.save
redirect_to #thing
else
render "new"
end
end
def profile
#things = Thing.where(user_id: current_user)
end
def show
end
def edit
end
def update
if #thing.update(thing_params)
redirect_to #thing
else
render "edit"
end
end
def destroy
if #thing.destroy
redirect_to root_path
else
redirect_to #thing
end
end
private
def thing_params
params.require(:thing).permit(:title, :description, :image).merge(zipcode: current_user.zipcode)
end
def find_thing
#thing = thing.find(params[:id])
end
def authenticate_user_first
if current_user != thing.find(params[:id]).user
redirect_to #thing
else
end
end
end
Can anyone help? Help is greatly appreciated.
There are two things that aren't connected to each other.
First, there is the deprecation warning. Because it is just a warning, not an error, you can choose to ignore it at the moment. If you want to remove the warning, just follow its instruction and change this line
if self.user.things(:reload).count >= 2
to
self.user.things.reload.count >= 2
Seconds, your code works like expected. Rails validations do not raise any errors, but they add error messages to the object. Just make sure that you display the errors to the user. To display the error you added to :base, add something like the following to your new.html.erb view:
<% if #thing.errors[:base].any? %>
<div class="error_message">
<%= #thing.errors.full_messages_for(:base).to_sentence %>
</div>
<% end %>
UPDATE: I have solved the NilClass issue! Thanks!
Now I am having a problem with:
unknown attribute 'sessionId' for Room.
SOLVEDI am currently having some issues where my code is telling me I have an error of "undefined method `create_session' for nil:NilClass" on line 9. I will provide the files.
This is the specific line:
#new_room = Room.new(strong_param)
rooms_controller.rb
class RoomsController < ApplicationController
require "opentok"
before_filter :config_opentok,:except => [:index]
def index
#rooms = Room.where(:public => true).order("created_at DESC")
#new_room = Room.new
end
def create
session = #opentok.create_session :media_mode => :routed
params[:room][:sessionId] = session.session_id
#new_room = Room.new(strong_param)
respond_to do |format|
if #new_room.save
format.html { redirect_to(“/party/”+#new_room.id.to_s) }
else
format.html { render :controller => ‘rooms’, :action => “index” }
end
end
end
def party
#room = Room.find(params[:id])
#tok_token = #opentok.generate_token #room.sessionId
end
private
def config_opentok
if #opentok.nil?
#opentok = OpenTok::OpenTok.new ########, "#########################################"
end
end
def strong_param
params.require(:room).permit(:name,:sessionId)
end
end
rooms.rb (Models)
class Room < ActiveRecord::Base
end
I've tried several different modifications to these files to make my program work. I can get the listing page to work but once I try and actually create a new room, I receive this error message.
Look forward to any advice you can provide.
You are missing the before_filter :config_opentok,:except => [:index] line from the blog post in your previous post (https://railsfornovice.wordpress.com/2013/01/01/video-chatting-in-ruby-on-rails/)
i have this controller
class StoresController < ApplicationController
before_filter :authenticate_business!, :except => [:index, :show]
def index
##stores = Store.paginate(:page => params[:page])#, :per_page => 8)
if params[:query].present?
#stores = Store.search(params[:query], page: params[:page])
else
#stores = Store.all.page params[:page]
end
end
def show
#store = Store.friendly.find(params[:id])
if request.path != store_path(#store)
redirect_to #store, status: :moved_permanently
end
end
def new
#store = Store.new
end
def create
#store = Store.new(store_params)
#store.business_id = current_business.id
if #store.save
redirect_to #store
else
render 'new'
end
end
def edit
#store = Store.friendly.find(params[:id])
end
def update
#store = Store.friendly.find(params[:id])
if #store.update(store_params)
redirect_to #store
else
render 'edit'
end
end
def destroy
#store = Store.friendly.find(params[:id])
#store.destroy
redirect_to stores_url
end
private
def store_params
params.require(:store).permit(:name, :description, :address, :telephone, :email, :website)
end
end
and a view with a form to create a new store.
<%= form_for #store do |f| %>
.......
code
......
<% end %>
The problem is that when i submit the form, it gives me this error "param is missing or the value is empty: store", pointing at line "params.require(:store).permit(:name, :description, :address, :telephone, :email, :website)"
Any idea to solve this problem?
Thank you.
I had this same issue and it was caused by a route issue, as discussed in the comments, causing the form not to post any data.
I think what you need is to make sure 'get' requests to the 'new' route access your 'new' method, while 'post' requests to the 'new' route access your 'create' method. Something like:
get 'stores/new' => 'stores#new'
post 'stores/new' => 'stores#create'
Rails 3.0.3
ruby 1.9.2p0
The Problem:
I have a Users table which has many items, the item(s) in turn therefore belongs to the Users.
In my model item.rb i attempt to save the item along with the value for the user.id so i have:
self.User_ID = #user.id
this however give me the error
Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
this is causing some confusion that it can't find this as in the show.html.erb that 'wraps' this page <%= #user.id %> displays the correct ID on the page
Many thanks in advance
** EDIT **
The Shorten action is the action upon which i want to parameter to be passed
class ItemsController < ApplicationController
def redirect
#item = Item.find_by_shortened(params[:shortened])
if #item
#redirect_to #item.original
redirect_to #item.original
else
redirect_to :shorten
end
end
def shorten
#host = request.host_with_port
#user = current_user
You need to load the #user model in every action that will require access to it. Having it render properly in the show action will not guarantee it is loaded in the update action.
Usually you need to have something like this in your controller:
class UsersController < ApplicationController
before_filter :load_user, :except => [ :index, :new, :create ]
# ...
protected
def load_user
#user = User.find(params[:user_id] || params[:id])
rescue ActiveRecord::RecordNotFound
render(:text => 'Record not found')
end
end