Update column through expiry in rails 4 - ruby-on-rails

An user should vote for a celebrity only once in 24 hours. So I need to update a votes column in user table. What I am doing here is that I am checking whether the current user has voted. If not I am allowing him to vote.
My models are
vote.rb
attr_accessible :celebrity_id, :user_id
belongs_to :user
belongs_to :celebrity, counter_cache: true
user.rb
attr_accessible :email, :name, :uid, :provider, :vote
has_many :votes
celebrity.rb
attr_accessible :name, :gender, :category_id, :image, :votes_count
belongs_to :user
belongs_to :category
has_many :votes
My controller
#celebrities = Celebrity.find(params[:id])
#vote = current_user.votes.build(celebrity_id: #celebrities.id, :id => params[:vote])
respond_to do |format|
if current_user.vote != true
current_user.vote = true
current_user.save
#vote.save
format.json { render json: #vote, status: :created }
else
format.json { render json: #vote.errors, status: :unprocessable_entity}
end
end
But, how can I set vote column in user table to zero every 24 hrs comparing to votes table created_at time

Related

3rd level nested model not receiving grandparent ID in form

I have a 3 models. User, CV, and Language. A User has one CV. A CV has many Languages. The User has many Languages through its CV. When I try to save the form I get an error that the Language does not have a User ID. How can I get the User ID to pass through the CV and to the Language in my form?
The CV is receiving the User ID properly. Languages is not.
I am using the Simple-Form and Cocoon gems.
Simplified version of form
= simple_form_for(#cv, url: user_cvs_path) do |f|
= f.simple_fields_for :languages do |language|
From User Model
has_one :cv, dependent: :destroy
has_many :languages, through: :cv, inverse_of: :user
From Cv Model
belongs_to :user
has_many :languages, dependent: :destroy
accepts_nested_attributes_for :languages, allow_destroy: true
From Language Model
belongs_to :user
belongs_to :cv
From the CV Controller
before_action :set_user
def new
#cv = #user.build_cv
#cv.languages.build
end
def create
#cv = #user.create_cv(cv_params)
respond_to do |format|
if #cv.save
format.html { redirect_to user_cv_url(#user, #cv), notice: 'Cv was successfully created.' }
format.json { render :show, status: :created, location: #cv }
else
format.html { render :new }
format.json { render json: #cv.errors, status: :unprocessable_entity }
end
end
end
def cv_params
params.require(:cv).permit(
:user_id,
:first_name,
:middle_name,
:last_name,
... # lots of params left out for brevity
languages_attributes: [
:id,
:cv_id,
:user_id,
:name,
:read,
:write,
:speak,
:listen,
:_destroy])
end
def set_user
#user = current_user if user_signed_in?
end
Your Language model does not need the belongs_to :user. Language belongs to CV and CV belongs to User, so the relation between Language and User is already in place. If you need to access the user for a specific language you can write #language.cv.user
To solve your problem just remove the belongs_to :user from the Language model, remove the user_id from languages_attributes, and remove the user_id from languages table.

Ruby on Rails : Updating multiple models in a single form

I have 3 models User, House and Order.
Order Model
class Order < ActiveRecord::Base
belongs_to :from_house, :class_name => "House"
belongs_to :to_house, :class_name => "House"
belongs_to :user
accepts_nested_attributes_for :from_house, :to_house, :user
end
My House Model.
class House < ActiveRecord::Base
belongs_to :user
belongs_to :place
belongs_to :city
end
My user model.
class User < ActiveRecord::Base
has_many :orders
has_many :houses
end
In my order form I have something like this
<%= form_for #order do |f| %>
... # order fields
<%= f.fields_for :user do |i| %>
... # your from user forms
<% end %>
<%= f.fields_for :from_house do |i| %>
... # your from house forms
<% end %>
<%= f.fields_for :to_house do |i| %>
... # your to house forms
<% end %>
...
<% end %>
I haven't changed much in controller from the default. The controller code
def create
#order = Order.new(order_params)
respond_to do |format|
if #order.save
format.html { redirect_to #order, notice: 'Order was successfully created.' }
format.json { render action: 'show', status: :created, location: #order }
else
format.html { render action: 'new' }
format.json { render json: #order.errors, status: :unprocessable_entity }
end
end
def order_params
params.require(:order).permit( :shift_date, user_attributes: [:name, :email, :ph_no], from_house_attributes: [:place_id, :floor, :elevator, :size], to_house_attributes: [:place_id, :floor, :elevator])
end
When I submit the form, as expected a Order gets created with a new from_house and to_house along with a new user. But however my user_id in house table remains NULL. How can I make the houses(both from and to) reference the user created after submit.
The User is not logged in, So there is no current_user. We have to create a new user based on the details given. That user has to be associated with the houses (from and to).
I hope I'm clear. If not please let me know.
P.S: This question is an extension to this Ruby on rails: Adding 2 references of a single model to another model
I think this change in app/models/order.rb should do the trick:
class Order < ActiveRecord::Base
belongs_to :user
belongs_to :from_house, class_name: 'House'
belongs_to :to_house, class_name: 'House'
accepts_nested_attributes_for :user, :from_house, :to_house
validates :user, :from_house, :to_house, presence: true
def from_house_attributes=(attributes)
fh = build_from_house(attributes)
fh.user = self.user
end
def to_house_attributes=(attributes)
th = build_to_house(attributes)
th.user = self.user
end
end
Now, try this in your Rails console:
params = { user_attributes: { name: 'New name', email: 'name#example.com' }, from_house_attributes: { name: 'From house name' }, to_house_attributes: { name: 'to house name' } }
o = Order.new(params)
o.save
o.from_house
o.to_house
Cheers!

False name? Patient::Diagnosi

I have to models:
class Patient < ActiveRecord::Base
attr_accessible :bis_gultigkeit, :geburtsdatum, :krankenkassennummer, :kvbereich, :landercode, :name, :namenszusatz, :plz, :statuserganzung, :strasse, :titel, :versichertennumer, :versichertenstatus, :vorname, :wohnort, :geschlecht, :telefon, :email, :gewicht
has_many :diagnosis
end
class Diagnose < ActiveRecord::Base
attr_accessible :beschreibung, :code, :seite, :sicherheit, :typ, :patient_id
belongs_to :patient
end
How you can see the two models have an association.
So that i want to display on the patient show page all of his diagnosis.
def show
#patient = Patient.find(params[:id])
#diagnosis = #patient.diagnosis
respond_to do |format|
format.html # show.html.erb
format.json { render json: #patient }
end
end
And in my view i call:
<%= #diagnosis.inspect %>
But somehow i get the error:
uninitialized constant Patient::Diagnosi
I cannot explain me why i get this error? And why does it say Diagnosi? I mean my model name is Diagnose! Thanks
You can call Diagnose.class_name.pluralize to see how rails pluralizes it.
I guess it is "Diagnoses", so you shoudl call:
#diagnoses = #patient.diagnoses
and
<%= #diagnoses.inspect %>

Rails behaving strange

I have rails version 3.2.13 and ruby version 1.9.3.
I have caught into very strange and interesting situation.
In my application have a model 'Product' with custom validator.
product.rb
class Product < ActiveRecord::Base
attr_accessible :description, :name, :price, :short_description, :user_id
validates :name, :short_description, presence: true
validates :price, :numericality => {:greater_than_or_equal_to => 0}
validate :uniq_name
belongs_to :user
belongs_to :original, foreign_key: :copied_from_id, class_name: 'Product'
has_many :clones, foreign_key: :copied_from_id, class_name: 'Product', dependent: :nullify
def clone?
self.original ? true : false
end
private
#Custom validator
def uniq_name
return if clone?
user_product = self.user.products.unlocked.where(:name => self.name).first
errors[:name] << "has already been taken" if user_product && !user_product.id.eql?(self.id)
end
end
In products controller's create action when I am trying to create new product
def create
#product = current_user.products.new(params[:product])
respond_to do |format|
if #product.save
format.html { redirect_to #product, notice: 'Product was successfully created.' }
format.json { render json: #product, status: :created, location: #product }
else
#product.errors[:image] = "Invalid file extension" if #product.errors[:image_content_type].present?
format.html { render action: "new" }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
Custom validator is being called when this line executed #product = current_user.products.new(params[:product]) and line # 2 of custom validator giving me error
undefined method `products' for nil:NilClass
I have inspected product object in custom validator but user_id is nil.
Why user_id is not being autoassigned?
Your help will be appreciated :)
So ... bypassing your question. Why aren't you just validating the uniqueness of name?
validates_uniqueness_of :name, :unless => :clone?
try to change .new to .build
#product = current_user.products.build(params[:product])
and be sure that you have relation in your User model
Class User < ActiveRecord::Base
has_many :products

mongoid can't push with HABTM relationship in rails

Im stuck on the issue a few days..Please help, thanks in advance.
This is a rails project on mongoid, there're 2 models in the project, one is User, another CustomSearchEngine:
class User
include Mongoid::Document
# Include default devise modules. Others available are:
......
# keep the CSEs
has_and_belongs_to_many :keeped_custom_search_engines, class_name: 'CustomSearchEngine', inverse_of: :consumers
# create or fork the CSEs
has_many :custom_search_engines, inverse_of: :author, dependent: :destroy
# Index
index({username: 1}, {unique: true, name: 'user_username'})
index({email: 1}, {unique: true, name: 'user_email'})
# Massive assignment for User.new
attr_accessible :email, :username, :agreement, :password, :password_confirmation
attr_accessor :agreement, :password_confirmation
validates :password_confirmation, presence: true
validates :agreement, presence: true
end
class CustomSearchEngine
include Mongoid::Document
include Mongoid::Timestamps
paginates_per 20
...
belongs_to :author, class_name: 'User', inverse_of: :custom_search_engines
has_and_belongs_to_many :consumers, class_name: 'User', inverse_of: :keeped_custom_search_engines
belongs_to :node
# Index
index({author_id: 1}, {name: 'cse_author_id'})
index({node_id: 1}, {name: 'cse_node_id'})
# validations
validates :status, presence: true, inclusion: {in: ['draft', 'publish']}
validates :author_id, presence: true
validates :node_id, presence: true
scope :recent, ->(status) { where(status: status).desc(:created_at) }
...
end
In my CustomSearchEngine controller:
current_user.keeped_custom_search_engines.push(#custom_search_engine)
Then I go to my mongodb, I see only the user document updated:
keeped_custom_search_engine_ids: ["50a208092061c770190000df"]
but the custom search engine document isn't changed:
consumer_ids: []
And I get an error: #messages={:consumers=>["is invalid"]}
Something I missed?
I think this problem is you push consumers before consumer instance save to database.
Try code like this:
def create
#team = Team.new(params[:team])
#team.own = current_user
respond_to do |format|
if #team.save
current_user.push_join_teams(#team.id)
format.html { redirect_to #team, notice: 'Team was successfully created.' }
format.json { render json: #team, status: :created, location: #team }
else
format.html { render action: "new" }
format.json { render json: #team.errors, status: :unprocessable_entity }
end
end
end
#user.rb
def push_join_teams(tid)
return false if self.join_team_ids.include?(tid)
self.push(:join_team_ids,tid)
end

Resources