Load model resources angular.js - ruby-on-rails

I have 2 tables posts and photos and there relationship is
post has_many :photos
photos belongs_to :posts
I load the posts through angular and display them to the user and all the content works perfect but when I try to display the photos they just don't show heres the code I am using
...loop through results
//this works
<h2>{{post.title}}</h2>
//this doesn't
<img src="{{post.photos.first.image}}" />
...end
I have been using Ruby on Rails and this is the syntax they use, I know its probably wrong but does anybody know the correct syntax.
Thanks

Try:
<img ng-src="{{post.photos[0].image}}" />
But check the model (the JSON return from Firebug, or debug from Firebug) to make sure the photos field exists and is array. The [0] should take the first item, if it exists. If it doesn't, you should better hide the image with ng-if.
Also make sure the path given by .image is correct for your application, you may need to enhance it as: ng-src="/correct/path/{{post.photos[0].image}}".

Related

Basic rails joins.. Result is a resource

I'm quite new to rails and making an app that lists albums.
Each album should be loaded with two or three preview tracks from that album.
All I want to do is get the preview_url from the previews table where the album_id is the same as the current album.
In mysql, I would use a left join:
SELECT preview_id FROM previews WHERE album_id = '{$sanitized_album_id}'...
I'm just not sure how to achieve this in ruby.
I can't find a single example that isn't obsessed with posts and comments, and it just isn't clear enough to click yet.
My album controller method looks like this:
def show
#previews = Preview.where(album_id: #album.id).order(track_number: :asc)
end
And my show.html.erb file should loop the results with this (simplified) code:
<% #previews.each do |preview| %>
<iframe src="<%= preview %>"></iframe>
<% end %>
Although I see no errors and the right number of previews are loading for each album, the resulting code is nonsense to me.
I expect the preview variable inside the do loop to be something like
https://website.com/previews/1984628754234
Instead, it looks more like this:
#<Preview:0x00007fcc08572c38>
I guess this is the database resource or something, but not the actual data I [think I] requested.
All the youtubes and whatnot didn't help me and I've only got a few hairs left...
Any one of you fantastic coders able to spare a moment to show me my stupid mistakes?
Thank you!
This will load all the attributes of Preview, it internally is performing a SELECT *.
#previews = Preview.where(album_id: #album.id)
if looping through #previews you would need to call preview.preview_id on each entry to get the value for that column.
In order to get a query like you showed - SELECT preview_id - you could use Preview.where(album_id: #album.id).select(:preview_id). You would still need to call .preview_id on each entry in the list, but it wouldn't load additional data.
If you want to make a query but you just want the plain array of preview_id values, you can use Preview.where(album_id: #album.id).pluck(:preview_id).
See:
select
pluck
That's a Preview instance. You probably want a field on Preview like:
<iframe src="<%= preview.preview_url %>"></iframe>
You can't just load in the model.

Rails - How to assign temporary id of a post to reference images

I have a simple blog site built on rails. I have a Post model and Picture model.
A Post has_many pictures and
A Picture belongs_to post
Below is what I want to achieve -
When I start to create new post, I will provide a link in the form that opens up a new window where I can upload multiple reference images with some name field as well.
Then I will use a macro string in my post body like ##IMG_<image-name>##.
I will dynamically create a new <img> tag to display relevant images, while the user is still creating the post.
My Problems -
As you know, during the time of post creation, I will not have a post_id.
Then how do I relate the reference_images being uploaded to a particular post?
Can I somehow assign a temporary-id to the post as soon as I enter create page and then after I save the post, anyway rails will takeover?
Hope you got where I am stuck. Please help!
Thanks in advance.
I appreciate all the responses you have given. But I had to achieve this is another hacky way for my needs -
HTML
I provided a <input type="file" id="refImg" onchange="javascript: uploadImage(this);">.
After the user has selected the required image, the uploadImage() funtion would create a dynamic form and do an AJAX POST to a distinct API. http://example.com/uploadImage
Rails
In rails controller referenceImages#uploadImage, I used paperclip to upload the image to cloudinary. The cloudinary upload call will return back with the image URL, if the upload is successful.
I responded with this URL in the JSON format.
JS
In javascript function uploadImage(), in the success function of ajax call, I parsed the URL from the response and dynamically created a <img src="parsed_image_url"> tag and appended it to the current cursor position of post body.

Using Ruby/Rails To Programmatically Post Form Data To Another Site

I'm trying to figure out a way to automate posting data on this site which does not have an API and thankfully not a captcha as well.
For example there is a form here => http://www.austinchronicle.com/gyrobase/EventSubmission
By examining the form I can figure out that the Name text box is setup as follows......
<input type="text" name="Name" id="EventName" value="" class="rejectPipe">
Using Ruby/Rails is there a way I can programmatically POST to the form on that page through the controller or in a rake task?
I sniffed out some links like => http://biodegradablegeek.com/2008/04/how-to-post-form-data-using-ruby/
and that seems to sort of explain the basic premise but what about inserting data into the time control or the drop down select boxes on another site? Or pretty much anything more complicated than inserting a string into an input box
Your best bet is to use something like Mechanize. I've written a blog post on a related subject (uploading data with Mechanize) : http://davidsulc.com/blog/2011/11/13/uploading-data-using-mechanize/
Alternatively, if you want to see the page while information is being entered, you could user Selenium http://davidsulc.com/blog/2011/11/27/automating-web-site-interactions-with-selenium/
You can use Typhoeus
For datetime selects you need conform to Rails protocol. Just pop open the source of the page and look at the names of their elements and use the same structure when posting. Do the same with select boxes

Rails 3.1 build GET form that creates a custom URL route that is SEO friendly

I would like to create custom SEO friendly routes similar to what is used by http://realestate.com.au For example the following page is shown by google when the search term "real estate melbourne" is used:
www.realestate.com.au/buy/in-melbourne,+vic+3000/list-1
I would like use the following format. mysite.com/trips/search/melbourne-to-sydney/01-01-2011
I have configured the routes in my routes.rb file to get it to pick up the correct parameters when a url is entered is this format.
routes.rb
match '/trips/search(/:fl(-to-:tl(/:tripdate)))' => 'trips#someaction'
My question is how do I setup a form in rails 3 to send a GET request using the above url structure. I have tried playing around with to_params though it seems to then change all my edit, show links etc which is not intended. I could build the link using javascript though I guess this would be a hacky option and the site would not work if javascript was disabled.
Is there a neat way to be able to create a GET submit form in Rails 3.1? The fields are select lists containing name and ids.
Thanks for your help.
This will help you immensely with the friendly URL portion
http://norman.github.com/friendly_id/file.Guide.html
https://github.com/norman/friendly_id

Ajax on Rails - I'm having an issue

I'm working on a Ruby on Rails web app, in which I've got several lists of posts. Each post will use Ajax to load their comments. In order of populating them in the right place, I'm doing the following:
Each post has a div with an id formatted as follows: <div id="my_div_<%= post.id %>"></div>. So, for example if the post.id is 12, the id will be "my_div_12".
My controller's action looks like this:
render :update do |page|
page.replace_html 'my_div_' + params[:post_id].to_s, :partial => 'my_comments_section_partial_path'
end
That works fine only if I have a post only once at the page. But in this site, each post might be listed more than once, because there are several lists (latest posts, popular, tops, etc). And all of them will have their Comments section to show.
The issue now is that, as the comments section functionality is inside a partial view, it will work the same for every type of list (as it's expected), and therefore, it doesn't make the difference between the divs (because they will have the same post.id, and thus, the same div's id).
My question now is: how could I solv this problem? Is there a better and different way for doing this?
Thanks in advance!
EDIT:
Just to clarify what I want, in few words:
I would like the code page.replace_html 'my_div_' + params[:post_id].to_s, :partial => 'my_comments_section_partial_path' to replace that partial in EVERY div called 'my_div' + params[:post_id].to_s (because there may be more than one div in the same page with the same id).
Note that having several elements with the same id on one page produces technically invalid html. Many browsers won't even render all those id attributes (leaving one and erasing the rest).
One simple solution is to switch to using classes instead of ids. There can be multiple elements with the same class and each element can have more than one class.
I don't work with built-in ajax helpers in Rails, but google suggests it's possible.
It seems like you have two sets of posts on the same page and are worried about putting the comments for the correct post in the correct spot. I think making two Ajax requests would be fine. The URLs would probably be something like /posts/1/comments and /posts/2/comments. Essentially what you want is "all the comments for a given post". You could have a comments action on your posts controller to use your has_many :comments association from Post. Using the URL ID parameter you can supply the post ID. You could get the Post ID out of the markup through a custom ID attribute, a custom class, or a custom data-* attribute.
It looks like you're using RJS but I'd recommend using Prototype or jQuery to make the Ajax request and specify JSON data or HTML as the response, then append the JSON or HTMl in the correct spot.
In jQuery I'd grab the post ID, make the ajax request, then append the comment HTML. This is not tested, but roughly the idea in code.
var comments_div = $('.post .comments'); /* need a diff. comments div for each */
var post_id = $('.post').attr('data-post_id');
$.get({'/posts/'+post_id+'/comments', function(data){ comments_div.append(data); } });

Resources