I want to disable all link of users at a time after deactivating users. So, for that I wrote a code like this
def link_to(*user)
if user_link_disabled?(user.id)
return nil
else
super
end
end
def user_link_disabled?(user_id)
User.where(activation: false).pluck(:name).include?(user_id)
end
But I am getting this error
undefined method `id' for #<Array:0x007efee4667d00>
Could anyone please help me on this?
I would add a column to your users model:
deactivated => type boolean
user.deactivated? #will return true or false
In your view you can then use link_to_unless
link_to_unless(user.deactivated, name, options = {}, html_options = {}, &block)
I don't know the scope because you didnt display anymore info but it could just be user_id in your if statement or try id[params[:id] instead of user.id but I'm not sure with out more context.
IN following method
def user_link_disabled?(user_id)
User.where(activation: false).pluck(:name).include?(user_id)
end
You are going to pluck name from user table records but you are checking include? for user.id, I think you should pluck id instead of name.
First of all, I am not gonna comment on your preferred code/method for overriding the the link_to helper. There is not much context available for that.
But to solve the particular error you are getting:
Your are defining method like this def link_to(*user) .
Here *user means it is expecting an Array as argument to the method and using the Ruby splat(*), it is converting it to normal arguments.
So if you call this as link_to [1,2,3], it will be same as calling a method with 3 arguments. That is link_to (1,2,3) but the argument user will be an Array.
So in here if user_link_disabled?(user.id), you are calling a id on a Array data type. That's why you are getting an error.
Depending on your use, either remove the * from method definition,
or
Use looping, if you are going to pass multiple users data to method, like:
def link_to(*user)
user.each do |u|
if user_link_disabled?(u.id)
return nil
else
super
end
end
end
As I mentioned in beginning, I don't know much about the context. So can not comment about the right way but if I may suggest, then I would suggest to use a custom helper for all user routes. like below pseudo code:
def link_to_user(user)
deactivated = user.deactivated?
if deactivated
# render some disabled link
else
# render link
end
end
Related
I have this function in rails controller:
def validate_params(*props)
props.each do |prop|
unless params[prop].start_with?('abc')
# return error
end
end
end
im thinking if I have params[:name] and params[:bio] and I want to validate name & bio with this function (not every attribute I might want to validate), I will call it with validate_params(:name, :bio). But, for nested param it won't work like params[:user][:name]. Is there anything I can do to pass this nested property to my function or is there a completely different approach? Thanks
Rails Validations generally belong in the model. You should post some additional info about what you're trying to do. For example, if you wanted to run the validation in the controller because these validations should only run in a certain context (i.e., only when this resource is interacted with from this specific endpoint), use on: to define custom contexts.
If you don't want to do things the rails way (which you should, imo), then don't call params in the method body. i.e.
def validate_params(*args)
args.each do |arg|
unless arg.start_with?('abc')
# return error
end
end
end
and call with validate_params(params[:user], params[:user][:name]
but yeah... just do it the rails way, you'll thank yourself later.
I need to set the id parameter to a value if it is wasn't submitted with the form.
Is it ok to do something like this in Rails or does this violate any standards or cause possible issues?
if params[:cart][:cart_addresses_attributes]["0"][:id].blank?
params[:cart][:cart_addresses_attributes]["0"][:id] = 1234 #default id
end
My implementation works with this logic, but I am not sure if this is the proper way to handle the issue.
There's a chance [:record_type] is nil which will lead to an undefined method error when you attempt to call [:id] on nil. Additionally, I'd find it a bit weird to directly mutate params, even though you technically can do that. I'd consider using Strong Parameter processing methods like so (added a full action, which isn't in your sample, to give more context on how this would be used):
def create
#record_type = RecordType.new(record_type_params)
if record_type.save
redirect_to #record_type
else
render :new
end
end
def record_type_params
params.require(:record_type).permit(:id).reverse_merge(id: 1234)
end
The reverse_merge call is a way to merge the user-supplied parameters into your defaults. This accomplishes what you're after in what I would consider a more conventional way and doesn't mutate params.
def cart_params
params.require(:cart).permit(:cart_addresses_attributes => [:id]).tap do |p|
p[:cart_addresses_attributes]["0"][:id] ||= 1234
end
end
if params[:record_type][:id].nil? # or replace ".nil?" with "== nil"
params[:record_type][:id] = 1234
end
personally, this is the way I prefer to do it. Some ways are more efficient than others, but if that works for you I'd roll with it.
I'm trying to monkey patch ActiveRecord::FinderMethods in order to use hashed ids for my models. So for example User.find(1) becomes User.find("FEW"). Sadly my overwritten method doesn't get called. Any ideas how to overwrite the find_one method?
module ActiveRecord
module FinderMethods
alias_method :orig_find_one, :find_one
def find_one(id)
if id.is_a?(String)
orig_find_one decrypt_id(id)
else
orig_find_one(id)
end
end
end
end
Here's an article that discusses how to actually do what you want by overriding the User.primary_key method like:
class User
self.primary_key = 'hashed_id'
end
Which would allow you to call User.find and pass it the "hashed_id":
http://ruby-journal.com/how-to-override-default-primary-key-id-in-rails/
So, it's possible.
That said, I would recommend against doing that, and instead using something like User.find_by_hashed_id. The only difference is that this method will return nil when a result is not found instead of throwing an ActiveRecord::RecordNotFound exception. You could throw this manually in your controller:
def show
#user = User.find_by_hashed_id(hashed_id)
raise ActiveRecord::RecordNotFound.new if #user.nil?
... continue processing ...
end
Finally, one other note to make this easier on you -- Rails also has a method you can override in your model, to_param, to tell it what property to use when generating routes. By default, of course, it users the id, but you would probably want to use the hashed_id.
class User
def to_param
self.hashed_id
end
end
Now, in your controller, params[:id] will contain the hashed_id instead of the id.
def show
#user = User.find_by_hashed_id(params[:id])
raise ActiveRecord::RecordNotFound.new if #user.nil?
... continue processing ...
end
I agree that you should be careful when doing this, but it is possible.
If you have a method decode_id that converts a hashed ID back to the original id, then the following will work:
In User.rb
# Extend AR find method to allow finding records by an encoded string id:
def self.find(*ids)
return super if ids.length > 1
# Note the short-circuiting || to fall-back to default behavior
find_by(id: decode_id(ids[0])) || super
end
Just make sure that decode_id returns nil if it's passed an invalid hash. This way you can find by Hashed ID and standard ID, so if you had a user with id 12345, then the following:
User.find(12345)
User.find("12345")
User.find(encode_id(12345))
Should all return the same user.
I am trying to output the value of a method on my Item model (current_user is defined in application_controller). I currently have as my rabl template:
object #item
attributes :id, :name
code :is_liked do |this_item|
if current_user
this_item.is_liked current_user
else
false
end
end
and in my model:
class Item < ActiveRecord::Base
...
def is_liked user
if user
if user.liked_item_ids.include?(self.id)
return true
else
return false
end
end
end
....
end
but it isn't working. I'm not sure what a proper way of outputting this would be. Any idea how to get this to work correctly?
edit 1
Here's the error that I'm getting:
Failure/Error: Unable to find matching line from backtrace
ActionView::Template::Error:
stack level too deep
Your rabl seems to be fine, however, when your find yourself adding some logic in your views (rabl can be compared to a view) you might want to consider refactor the logic in a presenter.
More information about presenters with rabl here
Regarding your error, like #apneadiving just said, there is a recursion issue in your codebase somewhere. Just by curiosity, have you try to rename the code block into something else than your method's name ? Depending on which version on rabl you are using, this could be the issue.
Finaly, you should consider refactoring your is_liked method:
def is_liked user
return user.liked_item_ids.include?(id) if user
false
end
Try:
node(:is_liked) {|this_item| this_item.is_liked(current_user) }
You already have the method, you can simply invoke here within a node instead of recreating logic.
I'm new to Ruby and I would like to find out what the best way of doing things is.
Assume the following scenario:
I have a text field where the user can input strings. Based on what the user inputs (after validation) I would like to access different fields of an instance variable.
Example: #zoo is an instance variable. The user inputs "monkey" and I would like to access #zoo.monkey. How can I do that in Ruby?
One idea that crossed my mind is to have a hash:
zoo_hash = { "monkey" => #zoo.monkey, ... }
but I was wondering if there is a better way to do this?
Thanks!
#zoo.attributes gives you a hash of the object attributes. So you can access them like
#zoo.attributes['monkey']
This will give nil if the attribute is not present. Calling a method which doesn't exist will throw NoMethodError
In your controller you could use the public_send (or even send) method like this:
def your_action
#zoo.public_send(params[:your_field])
end
Obviously this is no good, since someone can post somehing like delete_all as the method name, so you must sanitize the value you get from the form. As a simple example:
ALLOWED_METHODS = [:monkey, :tiger]
def your_action
raise unless ALLOWED_METHODS.include?(params[:your_field])
#zoo.public_send(params[:your_field])
end
There is much better way to do this - you should use Object#send or (even better, because it raises error if you try to call private or protected method) Object#public_send, like this:
message = 'monkey'
#zoo.public_send( message )
You could implement method_missing in your class and have it interrogate #zoo for a matching method. Documentation: http://ruby-doc.org/core-1.9.3/BasicObject.html#method-i-method_missing
require 'ostruct' # only necessary for my example
class ZooKeeper
def initialize
#zoo = OpenStruct.new(monkey: 'chimp')
end
def method_missing(method, *args)
if #zoo.respond_to?(method)
return #zoo.send(method)
else
super
end
end
end
keeper = ZooKeeper.new
keeper.monkey #=> "chimp"
keeper.lion #=> NoMethodError: undefined method `lion'