How to update datatime attribute? - ruby-on-rails-3

I just want to update the last_clicked_on:datetime attribute into current time.
class FeedEntriesController < ApplicationController
def show
#feed_article = FeedEntry.find(params[:id])
#feed_article.update_attributes(is_to_read: 'false')
#feed_article.update_attributes(last_clicked_on: Time.now)
#way = #feed_article.url
redirect_to #way
end
end
But the above code is not working. Please someone help me resolve this issue.

I guess you can try
#feed_article.is_to_read = 'false'
#feed_article.last_clicked_on = Time.now
#feed_article.save!
Anyway it's hard to help you with just this info. Issue might be in type of your columns, you can just misspell name of column... something else...
PS
Each update_attributes issue transaction in DB, so, you have 2 transactions instead of one... Code above will have only one transaction

Related

NameError Uninitialized Constant in rails for existing table

I'm a bit stuck on a problem here in Rails that I feel may have a simple solution.
I have a class called "CircuitVw" which looks like the following
class CircuitVw < ActiveRecord::Base
self.table_name = 'mvw_circuits'
self.primary_key = :serv_item_id
Inside the controller, I've been able to pull back data using the following format
CircuitVw.all().order("customer_name DESC").each do | circuit |
#customer[ "#{circuit.customer_name}" ] = circuit.psr
end
However, when I try and access the table written this way, I get an uninitialized constant
MVW_CIRCUITS.where("activity_ind IN ( 'Pending', 'In Progress')").order("document_number DESC").each do | circuit |
#psr[ "#{circuit.psr} - #{circuit.customer_name}" ] = circuit.psr
end
Even though I can say something like
SELECT * FROM MVW_CIRCUITS
And return the entire table in the console for my staging environment.
What am I doing wrong here?
The table exists in the schema as
create_table "mvw_circuits", id: false, force: true do |t|
for reference.
Thanks for any insights you might have! Maybe I'm forgetting something dumb. Appreciate any and all help.
You have to use CircuitVw to access or refer to the table mvw_circuits. You specified that in the CircuitVw class. So MVW_CIRCUITS is an uninitialized constant.
Try this one
CircuitVw.where("activity_ind IN ('Pending', 'In Progress')")

acts_as_list upper_limit on position

I am using acts_as_list on my model.I have a position column on that model for which I don't wan't the model object to be saved to the database if the position is more than my upper-limit.(I tried using rails validation for position, but apparently it seems that rails validation runs first then acts_as_list does it's job to update(increment) the position and save it in db.
Is something like this possible with acts_as_list scope: :widgets, {0 < :position <= 2}
I went through their documentation, but couldn't find anything.
How can I do it in Rails.
Any help will be much appreciated. please feel free to ask me for more info if you need.
I think you need to do something like this
acts_as_list scope: :widgets, if: 'position <= 2'
acts_as_list doesn't support this natively. You could try adding a validation based on there being no more than x records with the matching scope?
validates :maximum_records
private
def maximum_records
if where([[scope conditions]]).count > something
errors.add :base, 'too many records'
end
end

rails 3 temporary user input to use for comparison

I'm not sure how to even research this question so maybe some awesome rails developer can point me in the right direction.
I have a model that's holding a question and correct answer. On the show view, I want the user to enter their answer into an input field and upon pressing submit, their answer is compared to the one held in the model. I don't need to save their answer.
Thoughts?
You could use a non ActiveRecord model for that. Something like this:
class UserAnswer # note that this class doesn't inherit from ActiveRecord::Base
attr_accessor :question_id, :answer
def initialize(params)
#question_id = params[:question_id]
#answer = params[:answer]
end
def correct?
q = QuestionAnswerModel.find(self.question_id)
q.answer == self.answer
end
end
Then in your controller you can do something like this:
user_answer = UserAnswer.new(params) # params contains :question_id and :answer
user_answer.correct? # returns true or false
A simple way is to save the answer confirmation only if it is equal to the answer.
Model:
question
answer
answer_confirmation
Then proceed to make the form as you normally would.
In the model add
validate :check_answer
def check_answer
errors.add(:answer, "Must be the same as answer confirmation") if answer!= answer_confirmation
end

Change Attribute of another table

I have the table "tools" and "lend".
Im using Rails3 and when i create a lend i would like it change the attribute status of the tool to 'U'.
Would this is possible?
i tried on the model lend
after_save :change_status
def change_status
tools.update_attribute(status, 'U')
end
i tried too, on the same model:
after_save :change_status
def change_status
self.tool.update_attribute(status, 'U')
end
No success or warning on debug log.
Sugestions?
Thanks! :)
What is the relationship between lend and tool? If Lend has_many tools, you will have to do something like this:
def change_status
tools.each { |tool| tool.update_attributes(status: 'U') }
end
Note also that I am using update_attributes because update_attribute (singular) will be deprecated soon.
BTW, you should create a method in Tool to update the attribute, the Lend model should not be aware about how to set a tool as loaned. Something like
def loaned!
update_attributes status: 'U'
end
Firstly, I assume that your Lend model has_many :tools
In order to be able to do something like tool.update_attribute you'll need to work with the accepts_nested_attributes_for
Take a look at these links and they will probably set you on the right path:
RailsCasts #196 Nested Model Form Part 1
Active Record Nested Attributes
Hope this helps.

Unless statement in Rails controller?

I have the following code in my Rails 3 applications controller:
def like
#suggestion = Suggestion.find(params[:id])
#suggestion.voteip = request.env['REMOTE_ADDR']
#suggestion.update_attribute(:votes, #suggestion.votes + 1)
redirect_to suggestions_url
end
def dislike
#suggestion = Suggestion.find(params[:id])
#suggestion.voteip = request.env['REMOTE_ADDR']
#suggestion.update_attribute(:votes, #suggestion.votes - 1)
redirect_to suggestions_url
end
As you can see the code increments/decrements the vote integer by 1 and adds the users IP address to the column called voteip.
What I am trying to achieve is a simple block on votes from the same IP twice in a row. So if for example my IP was 123.123.123.123 and I voted on something, I couldn't then vote on the same suggestion again (either up or down) from the same IP address.
This is a really simple and nowhere near foolproof method of rate-limiting votes. Although, in the environment it's going to be used in it's almost perfect!
Once I've got this working I'm planning on adding another column for the vote timestamp, then I can do things like only allowing voting from the same IP after 5 minutes have passed.
Any advice would be appreciated!
One way to do it is to find the last vote which has the ip of the REMOTE_ADDR.
Add this in your controller.
def like
#suggestion = Suggestion.find(params[:id])
remote_addr = request.env['REMOTE_ADDR']
#last_vote = Suggestion.find_ip(remote_addr).last
if #last_vote.created_at < 2.minutes.ago
render :text => "get lost"
else
#suggestion.voteip = remote_addr
#suggestion.update_attribute(:votes, #suggestion.votes + 1)
redirect_to suggestions_url
end
end
And add this in your Suggestion model
def self.find_ip(ip)
where('voteip = ?', "#{ip}")
end
I created a quick app and tested it so it does work. Of course you can change the 2.minutes.ago to whatever time frame you want.
Hope this helps!
A vote is really a separate resource. Especially if you want to implement a more robust system in the future you'll want your votes to be a separate table, through a has_many relationship. This way it is super easy to compare when the last vote by a particular ip occurred (used as an index, or if the user is authenticated possibly the user_id). Also this allows you to create voting histories for IP's/Users.
User/ip has many suggestions which has many votes. Just my two cents.