Rails: friendly_id and to_json - ruby-on-rails

I have a collection of model objects that I am trying to return JSON for. E.G
#regions.to_json(:only => [:id, :name ])
that works fine.
If I try to use :
#regions.to_json(:only => [:friendly_id, :name ])
then nothing is returned for the friendly_id. The model does have:
has_friendly_id :name, :use_slug => true
So I am wondering what I am missing - or if I am not allowed to use
friendly_id's in to_json?

Try using
#regions.to_json(:only => [:id, :cached_slug])

Related

update_attributes validation fails though values are correct

I have in my model
class Account < ActiveRecord::Base
validates_length_of :amount, :in 1..255, :on => update, :if => Proc.new { |a| false if a.id == nil;a.amount.blank? }
validates_length_of :name, :in 1..255, :on => update, :if => Proc.new { |a| false if a.id == nil;a.name.blank? }, :unless => user_has_amount?
end
when I comment out the if condition, it works fine but with them validation fails which is confusing. I know that the validation should only run if the proc returns true or unless returns false
in my controller I have
#account.update_attributes({:name => "king", :amount => "1223"}
the save fails and when I check errors I get
#account.errors.details
{:name =>[{:error=>:too_short, :count=>1}], :amount =>[{:error=>:too_short, :count=>1}]}
Strong Params are not an issue because I have
def self.params
params.require(:account).permit!
end
I have no idea why it fails though the value are present and correct.
Try this the following:
class Account < ActiveRecord::Base
validates :amount, length: { in: 1..255 }, on: :update
validates :name, length: { in: 1..255 }, on: :update
end
Check your strong parameters. Your error tells you that something is wrong before you get to validation: :name =>[{:error=>:too_short, :count=>1}] This is saying that the minimum string count is 1 but that your string is not even that long. Here is the docs on that.
You can try: Account.find(1).update_attributes({:name => "king", :amount => "1223"} to see if #account is not being set properly.
You can also customize the language on your errors to help further:
validates_length_of : name, within: 1..255, too_long: 'pick a shorter name', too_short: 'pick a longer name'
The issue that was happening was for one reason. The code was inheriting from a class that had:
slef.reload
in one of the function that were being called during validations.
so every time we try to update the update failed because once that validation was hit it reloaded the original values from database and ignored new values which if old values are empty is just a head scratcher.
Thanks everyone for the help

rails render json nested two levels

How can I expand associations more than one level deep? Right now I can expand reviews but am not sure how to also expand the patient_profile_id?
class Review
belongs_to :patient_profile
end
render json: doctors.to_json(
:include => {:reviews => {:include => :patient_profile_id }}
)
I'd highly suggest you check out the jbuilder gem. There's a great railscast that explains it's usage.
Basically, you will have to add a jbuilder file into your views, that gives you allot more control over your json.
For your specific use case you'd use something like this:
doctors/index.json.jbuilder
json.doctors #doctors do |json, doctor|
json.(doctor, :id, :name)
json.reviews doctor.reviews do |json, review|
json.(review, :id, :rating, :patient_profile_id)
json.patient_profile review.patient_profile do |json, profile|
json.(profile, :id, :name, ... ) # attributes of the profile
end
end
end
Try to use something like this:
render json: doctors.to_json(
:include => {:reviews => {:include => :patient_profile }}
)
Here you can find detail information how to serialize nested objects.
Check for overriding as_json method

Rails 4, create multiple objects - how to permit it?

How to permit this parameters:
contacts: [
{:value => 'value', :contacts_type => 'contact_type'},
{:value => 'value', :contacts_type => 'contact_type'},
]
To create many objects by controller action in one JSON request?
Like below, contacts will be an array of resources with specific attributes value and contacts_type:
params.permit(contacts: [:value, :contacts_type])
If you get params like the following:--
:params=>{:xyz => {:contacts => [{:value => 'value', :contacts_type => 'type'}, ..]}}
Then do the folowing:--
params.require(:xyz).permit(contacts: [:value, :contacts_type])
And add attr_accessor :contacts to your model if contacts is just a form field name part.
Work around for this should be
def contact_params
new_params = params.permit(contacts: [:value, :contacts_type])
new_params[:contacts] if new_params
end
Please suggest alternate solution if any

Hobo, "Company.lost_is(false).apply_scopes"

The application I am about to develop is under migration from Hobo 1 to Hobo 1.0.3.
This is a line of code that does not work any more:
hobo_index Company.lost_is(false).apply_scopes(
:search => [params[:search], :name],
:order_by => parse_sort_param(:name, :last_call, :lost, :user, :country, :status, :sector), :user_is => user)
The problem here is lost_is which does not seem to return values acceptable by next routine which is: apply_scopes.
So... how can I solve this problem?
Maybe make some changes to make lost_is produce values acceptable by apply_scopes
Or maybe I could change params[:search] to search only for records with lost column set to false?
Thank you!
Jacek
Adding the condition to the scopes should work:
hobo_index Company.apply_scopes(
:lost_is => false,
:search => [params[:search], :name],
:order_by => parse_sort_param(:name, :last_call, :lost, :user, :country, :status, :sector),
:user_is => user)
Regards,
Ignacio

Can't save collection_select to object

I'm going crazy here.
I have:
class Course
belongs_to :commune
end
and
class Commune
has_many :courses
end
In the new view for Course I have a drop down where the user selects commune:
f.collection_select(:commune, get_commune_list, :id, :commune, { :prompt => true })
(The get_commune_list is a helper method that returns a list of Commune objects)
But when I try to save it I either get this error:
Commune(#2176182100) expected, got String(#2148246520)
or the Commune isn't saved on the Course object at all.
The parameters look like this:
{"course"=>{"price"=>"6000",
"title"=>"Some title",
"commune"=>"10",
...
}
I just can'† figure out why this won't work!
Shouldn't it be?
f.collection_select (:commune, :commune_id, get_commune_list, :id, :commune, { :prompt => true })

Resources