I want to update a prediction_config, but something is going wrong. Here are the relevant methods in my controller:
def edit
#prediction_config = PredictionConfigs.find(params[:id])
end
def update
#prediction_config = PredictionConfigs.find(params[:id])
if #prediction_config.update_attributes(params[:prediction_config])
redirect_to #prediction_config
else
render 'edit'
end
end
Here is my Model:
class PredictionConfigs < ActiveRecord::Base
attr_accessible :name, :value
validates :name, presence: true
validates :value, :inclusion => {:in => [0,100]},
presence: true
end
What could be the problem? Any help is appreciated!
EDIT: It is simply not updating the value, but everything loads properly.
Related
I have this password validation in my user.model.rb:
class User < ActiveRecord::Base
validates :password, presence: true, confirmation: true,
format: {:with => /^(?=.*[0-9])(?=.*[A-Z])(?=.*[&%$##*])[a-zA-Z0-9&%$##*]{8,}$/,
:multiline => true, :message => I18n.t('invalid_password')}
end
I want this validation to be called in each and every method but not in my update action.
I have a users_controller.rb that has a create and update action. I want it to check in the create action but not in the update action.
I also have a password_resets_controller.rb in which I want it to check in both create and update actions but not in users_controller update action. I am using the authlogic gem. Both controllers use the same model.
Please guide me on how to do this. Thanks in advance.
validates :password, :presence => {:on => :create}
OR
##here new_user is a method that you can create and use condionally
## or validates_presence_of :password, :if => :new_user?
validates_presence_of :password, :unless => :new_user?
def new_user?
//your code
end
OR Using with_options
class User < ActiveRecord::Base
has_many :roles
# Normal Validations
validates_presence_of :password
with_options :if => :customer? do |customer|
customer.validates_presence_of :password
end
def customer?
roles.any? { |role| role.name == "customer" }
end
end
Probably the most close answer can be:
class User < ActiveRecord::Base
validates :password, presence: true, if: :not_persisted?
def not_persisted?
!self.persisted?
end
end
This code will actually trigger the validation only if the object is not persisted (on create)
Hi i am using Bootsy and it is work fine, unfortunatly image upload option is not working I have already installed CarrierWave which is also working fine.
My form
<%= f.bootsy_area(:description) %>
My Model
class Page < ActiveRecord::Base
belongs_to :user
include Bootsy::Container
require 'carrierwave/orm/activerecord'
mount_uploader :attachment, AttachmentUploader
extend FriendlyId
friendly_id :title, use: :slugged
validates :title, :presence => true
validates :slug, :presence => true
validates :user_id, :presence => true
def should_generate_new_friendly_id?
new_record? || !self.slug.present? && self.title.present?
end
end
My controller
def pages_params
params.require(:page).permit(:title, :description, :status, :slug, :user_id, :password, :attachment, :bootsy_image_gallery_id)
end
def create
#page = Page.new(pages_params)
if #page.save
redirect_to(:action => "index")
else
render("new")
end
end
any any advice and suggestions will be greatly appreciated. thanks
Not sure if you have found the answer yet, here is what I found with the similar problem and its solution.
After upload images, how to insert the image?
I'm getting the error message about strong parameters. I think it's just that rails 4 doesn't use attributes anymore. the code for my toy.rb is:
class Toy < ActiveRecord::Base
attr_accessible :name, :price, :vendor
validates :name, :presence => true
validates :price, :presence => true
validates :price, :numericality => true
validates :vendor, :presence => true
end
how can I change this to strong parameters?
EDIT: I used a different rb i changed it to employees and this is what I have:
class Employee < ActiveRecord::Base
params.require(:employee).permit(:first, :last, :salary, :salary, :ssn)
validates :first, :presence => true
validates :last, :presence => true
validates :salary, :presence => true
validates :salary, :numericality => true
validates :ssn, :presence => true
end
It's still telling me "ndefined local variable or method `params' for #"
The code you need is
params.require(:toy).permit(:name, :price, :vendor)
You will put this in your controller. Typically, you create a private method:
def create
Toy.create(toy_params)
end
private
def toy_params
params.require(:toy).permit(:name, :price, :vendor)
end
See http://guides.rubyonrails.org/getting_started.html#saving-data-in-the-controller for more information.
Edit
I think I might have misled you with my original answer. The code goes in the controller, not the model.
Strong params are designed to help your controller send specific data to your model. It's meant to protect your app against unauthorized data being passed:
#app/controllers/toys_controller.rb
Class ToysController < ActiveRecord::Base
def new
#toy = Toy.new #-> creates a blank AR object
end
def create
#toy = Toy.new(toys_params) #->creates new AR object (populating with strong params)
#toy.save
end
private
def toys_params
params.require(:toys).permit(:your, :params, :here)
end
end
I'm fairly new to rails and I don't think I'm understanding the routing completely. When I try to access the edit action I get the following error:
ActiveRecord::RecordNotFound in StoreController#show
Couldn't find Gear with id=edit
Rails.root: /Users/dave/rails_projects/outdoor
Application Trace | Framework Trace | Full Trace
app/controllers/store_controller.rb:7:in `show'
Request
Parameters:
{"user_id"=>"104",
"id"=>"edit"}
Show session dump
Show env dump
Response
Headers:
None
Here is my view with the link that is throwing this error:
<li><%= link_to "Store Appearance", edit_user_store_path(#user) %></li>
Here is my nested route:
resources :users do
resources :store
end
Here is my controller
class StoreController < ApplicationController
def index
#store = current_user.gears.paginate(page: params[:page])
end
def show
#gears = Gear.find(params[:id]).user.gears.paginate(page: params[:page])
end
def edit
end
def update
end
end
Model Store
class Store < ActiveRecord::Base
attr_accessible :storeimage, :storename
belongs_to :user
validates :user_id, :presence => true
end
Model User
class User < ActiveRecord::Base
attr_accessible :first_name, :last_name, :email, :password, :password_confirmation, :userimage, :remove_userimage
has_secure_password
has_many :gears
has_many :comments, :dependent => :destroy
has_one :store, :dependent => :destroy
before_save :create_remember_token
require 'carrierwave/orm/activerecord'
mount_uploader :userimage, UserpicUploader
email_regex = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :first_name, presence: true,
length: {:maximum => 50 }
validates :last_name, presence: true,
length: {:maximum => 50 }
validates :email, presence: true,
format: {:with => email_regex},
uniqueness: {:case_sensitive => false}
validates :password, presence: true,
confirmation: true,
length: {within: 6..40}
include Tire::Model::Search
include Tire::Model::Callbacks
def name
first_name + " " + last_name
end
private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
end
Please help.
You need to pass both the user_id and id params in the URL when you're accessing a store object nested under a user, so your URL should look like this:
/users/1/stores/3/edit
Versus:
/users/1/stores/edit
You also need to pass both of those as arguments to your path helper, ie:
edit_user_store_path(#user, #store)
I have the following models (with corresponding database tables) in my Rails 3 application:
class User < ActiveRecord::Base
has_many :service_users
has_many :services, :through => :service_users
attr_accessor :password
attr_accessible :password, :password_confirmation, :service_ids
validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6..40 }
...
end
class Service < ActiveRecord::Base
has_many :service_users
has_many :users, :through => :service_users
...
end
class ServiceUser < ActiveRecord::Base
belongs_to :service
belongs_to :user
end
#User Controller:
class UsersController < ApplicationController
...
def update
#user = User.find(params[:id])
if #user.update_attributes(params[:user])
flash[:success] = "Profile updated."
redirect_to #user
else
#title = "Edit user"
render 'edit'
end
end
...
end
I want to be able to update a User model's associated services without having to specify the password and password confirmation attributes. How can I do this?
Two options...
If you have simple logic, like only validating the password when a user is created, this will work:
validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6..40 },
:if => :new_record?
More likely, you'll want a combination so that users can update their password:
validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6..40 },
:if => :is_password_validation_needed?
# Protect the password attribute from writing an
# empty or nil value
def password=(pass)
return if !pass.present?
#password = pass
end
private
def is_password_validation_needed?
# Return true if the record is unsaved or there
# is a non-nil value in self.password
new_record? || password
end
This could help:
http://railscasts.com/episodes/41-conditional-validations
you will want to look into conditional validation to specify whether or not the password attribute in your model should be validated when you are updating/saving the model. here is a Railscast episode that, while a little dated, is still fairly straightforward and should get you off on the right path