Using API in partial and passing values? - ruby-on-rails

I am trying to display some info from an API.
I have this code:
<% recco = Model.find_by_id(activity.trackable.id %>
Now, rendering the following line will output the ID I want:
<%= recco.item_id %>
However, when I want to link to this item and I need the name from the API, some of the code fails and some not. This is the line I have:
<%= link_to #client.author(recco.item_id).name, book_path(recco.item_id) %>
The book_path works and displays a link to the correct URL with the ID. The client that tries to get the name from the API returns that it is not found.
But, if I try remove the the recco.item_id and just hardcode it to:
<%= link_to #client.author("7").name, book_path(recco.item_id) %>
It works and displays the author name. Is there a special reason for the API request to not understand that the recco.item_id is a number? The book_path displays the link just fine.

It looks like the author method expects a string instead of an integer. All you have to do is add to_s to the item_id for it to work:
<%= link_to #client.author(recco.item_id.to_s).name, book_path(recco.item_id) %>
The reason why the API does not understand the integer you passed to it is likely because they did not logic have in that method to convert that passed argument into a string. Ideally, a public would try and convert whatever args are passed to it into the type of value it expects. The to_s we did on your method would ideally be in the API, but since you likely don't have control over the API code, you'll have to do the workaround yourself which doesn't take much effort anyway. :)

Related

Saving json response in create

I want to save a json response but it is saving the title instead of the value. Also having issues with how the params are coming through with slashes instead of as a hash
I have the following response from form submit:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"2134", "shipping_rate"=>{..."shipping_rate"=>"{\"serviceName\"=>\"USPS First Class Mail - Package\", \"serviceCode\"=>\"usps_first_class_mail\", \"shipmentCost\"=>2.66, \"otherCost\"=>0.0}"}, "commit"=>"Create Shipping rate"}
form:
...
<% #rates.each do |rate| %>
<%= form.radio_button :shipping_rate, rate.as_json %> <%= rate %><br />
<% end %>
...
I am under the impression using as_json removes the "/" so it comes through as a hash parameters.
I also tried using #rates.as_json.each with same results
Create method in controller:
#shipping_rate.service_code = params["shipping_rate"]["shipping_rate"]["serviceCode"]
How the service_code saves is as "serviceCode" and not "usps_first_class_mail".
How can I:
Have the params come through as a hash, without the /'s
Save the value of params["shipping_rate"]["shipping_rate"]["serviceCode"] instead of the title
rate.as_json is correctly returning a hash, but when you pass data to form.radio_button it get's converted into something html friendly. Basically, form.radio_button calls .to_s (or some similar method that probably also escapes html) on that hash, which is why you're getting the hash as a string.
As a rule, individual HTML form elements should not contain hash data, and especially not ruby formatted hash data. Keep in mind that once the page is rendered in a browser, it knows nothing about the backend, let alone how to run ruby code.
You should take a step back and think of this RESTfully. If your users are meant to select a rate, and you have a number of rate records in your db, you really only need them to send back the id of the rate they would like. Without seeing your controller it's hard to tell exactly what else would need to change, but your radio buttons should probably look more like:
<%= form.radio_button :rate_id, rate.id %>
Your controller's create method would then be responsible for setting the user's selected rate, possibly requiring you to look up the rate again.

Rail 4 image_tag with variable

I am trying to make a show page that displays an image based on the person called out of the database. My current code looks like this :
<%= image_tag('DAF_520x222.jpg') %>
I want to exchange the 'DAF_520x222' portion for a call of #user_name but I am unsure of how to go about putting this in the image_tag itself.
You can directly interpolate it into the string. It will automatically change it to its value
<%= image_tag("#{#user_name}.jpg") %>
This should work

eRuby - Understanding the Rails API

I'm on api.rubyonrails.org trying to read through some of these helpers to build out a form, but I keep getting errors like undefined method 'merge'. Unfortunately,
number_field(object_name, method, options = {})
Returns an input tag of type “number”.
doesn't help much at all. I've got that object_name is the name field for the generated input, but i'm fuzzy on what method, and options are used for. I just want a series of labels next to inputs, where clicking the label focuses the input, but all I can get is the first input focused regardless of the label you click.
The syntax I'm using is:
<%= f.label :item_data, i.name %> <%= f.number_field :item_data %>
i is an item from an each do. I realize this will give them all the same name, I'm just not sure what else to do about it.
The number_field is a method used to create an html input tag with type "number". Object_name is the name of the object of your form (say for instance, item). Method is the name of the actual field (for instance, cost). Options are any options you want to pass into the html field, like it being disabled, read-only, giving the tag a class/id, and so forth. If you don't pass in any options, the = {} means it just defaults to no options.
In conjunction with form_for, the syntax changes to something like this:
<%= form_for #item do |f| %>
<%= f.number_field :cost, id: "sample", class: "example" %>
<% end %>
Look at this documentation for more information on the options you can pass. Yes, it's different syntax, but the options will be the same.

What is a right way to update a boolean field using link_to. Getting undefined method `model_name' for TrueClass:Class

I have the below link_to in a loop in my rails app
<%= link_to 'Up', Product.find(n.id).update_attribute(:opinion, true)%>
But I am unable to update it. Because it gives me the error
undefined method `model_name' for TrueClass:Class
So, I am wondering in this case what is the right way to update a boolean field?
You are not updating the opinion after click the link, you are updating it when the page render.
Lets say your page has only the following code:
<%= link_to 'Up', Product.find(n.id).update_attribute(:opinion, true)%>
What actually happens when you hit that page is that the code wrapped on <%= %> is executed and used to generate an string, that will become your HTML. So while simplifying your expression, in one step of the execution you will have the following code:
<%= link_to 'Up', true %>
And this will generate the HTML
Up
Which is not what you intend of.
Solution
Create an action on your product controller that receives the product id, updates the product and redirects back. So, something like this:
On your route.rb
resource :products do
member do
post 'update_opinion'
end
end
On your products_controller.rb:
def update_opinion
Product.find(params[:id]).update_attribute(:opinion, true)
redirect_to :back
end
On your view:
<%= link_to 'up', update_opinion_project_path(n) %>
Your code does something very different from what you seem to be pursuing.
The helper method link_to accepts two parameters: the link text and the link target, which can be:
a string, like: 'http://stackoverflow.com';
a hash referring all the single components of an internal URL, as defined by routes;
an object, or an array of objects.
As second parameter, you are passing an expression:
Product.find(n.id).update_attribute(:opinion, true)
which is evaluated the first time the code runs, that is, during rendering.
The expression tries to update the attribute immediately and then returns a boolean that says if the operation succeeded or not: true if it successfully updated the attribute, false otherwise.
In your case, it appears to be successfully: it returns true.
Now, true is neighther a string nor an hash, so it is treated as an object, whose class is TrueClass. So it treats it as a model, but not being a model, it does not define the models methods; thus the error.
What you want to do is to put the code in a controller, and put the URL relative to the right controller action as second parameter of link_to.

rails form using database

i have a rails form ive made in which the form fields are extracted from the database. i did it like this because for different products, there are different form fields. i could have made one big order form to do it, and if the product field didnt apply to the product it would be left blank, but it seemed like making the fields being called from a database made more sense because there are 30-40 fields per order. anyways the error in which im running into is when im extracting the row field_type, it prints out the literal value instead of putting it in rails. heres what it looks like:
<% #form_field.each do |field| %>
<p>
<%= "f.#{field.field_type}" %> #this prints out f.text_field
</p>
<% end %>
Instead of printing out f.text_field, i would like it to actually make a text field. I tried using raw but no look seeing as thats for html. is there a way to do this in rails?
You'd need to build up the string and send it to f, like f.send(field.field_type) (untested) along with any arguments needed for that particular form field type.

Resources