Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9285939
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T19:17:31+00:00 2026-06-18T19:17:31+00:00

He I have two models in my rails application (Post, Picture) that are associated

  • 0

He

I have two models in my rails application (Post, Picture) that are associated as follows:

#Post model
has_many :pictures, :dependent => :destroy 
accepts_nested_attributes_for :pictures, :allow_destroy => true 

#Picture model
belongs_to :post

In my post edit view I have two forms, so I can edit the post content as well as add pictures to the post. I use the jquery file upload plugin together with carrierwave to handle the upload process. This looks quite similar to this setup here http://tinyurl.com/aun7bl5

When I go to the post edit view the jquery file upload always shows me all pictures, because it uses the index action of the picture controller which fetches all images and renders them to json so jquery file upload can handle them. The index action looks like this.

def index
  @pictures = Picture.all 
  render :json => @pictures.collect { |p| p.to_jq_upload }.to_json
end

The post param (:id) is available to the post controller when I edit a post. I can see it with the logger. But it is not available to the index action which is nested inside of the post edit form.

Now my question is, how I can provide the index action in the post controller with the id of the post I like to edit so that I can do there something like this to filter the pictures it gets:

def index
  @pictures = Picture.where(:post_id => params[:id])
  render :json => @pictures.collect { |p| p.to_jq_upload }.to_json
end

EDIT:

#Post#edit view
<div class=post-well>
  <div class="page-header">
    <h1>Reisebericht editieren</h2>
  </div>

  <%= simple_form_for @post do |f| %>
    <%= f.error_notification %>
    <div class="form-inputs">
      <%= f.input :title, :label => "Titel", :input_html => { :class => 'new-post-inputfields' } %>
      <%= f.input :body, :label => "Artikel", :input_html => { :class => 'new-post-inputfields' } %>
      <%= f.hidden_field :picture_ids, :input_html => { :id => 'post_picture_ids' } %> 
      <%= f.button :submit, :label => "Speichern" %>
    </div> 
  <% end %>

  <h4>Bilder verwalten</h4>
  <%= simple_form_for Picture.new, :html => { :multipart => true, :id => "fileupload"  } do |f| %>
    <!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
    <div class="row fileupload-buttonbar">
      <div class="span7">
        <!-- The fileinput-button span is used to style the file input field as button -->
        <span class="btn btn-success fileinput-button">
          <i class="icon-plus icon-white"></i>
          <span>Hinzufügen</span>
          <%= f.file_field :path, multiple: true, name: "picture[path]" %>
        </span>
        <button type="submit" class="btn btn-primary start">
          <i class="icon-upload icon-white"></i>
          <span>Upload</span>
        </button>
        <button type="reset" class="btn btn-warning cancel">
          <i class="icon-ban-circle icon-white"></i>
          <span>Abbrechen</span>
        </button>
        <button type="button" class="btn btn-danger delete">
          <i class="icon-trash icon-white"></i>
          <span>Delete</span>
        </button>
        <input type="checkbox" class="toggle">
      </div>
      <div class="span5">
        <!-- The global progress bar -->
        <div class="progress progress-success progress-striped active fade">
          <div class="bar" style="width:0%;"></div>
        </div>
      </div>
    </div>
    <!-- The loading indicator is shown during image processing -->
    <div class="fileupload-loading"></div>
    <br>
    <!-- The table listing the files available for upload/download -->
    <table class="table table-striped"><tbody class="files" data-toggle="modal-gallery" data-target="#modal-gallery"></tbody>
    </table>
  <% end %>
</div> 

<script>
  var fileUploadErrors = {
    maxFileSize: 'File is too big',
    minFileSize: 'File is too small',
    acceptFileTypes: 'Filetype not allowed',
    maxNumberOfFiles: 'Max number of files exceeded',
    uploadedBytes: 'Uploaded bytes exceed file size',
    emptyResult: 'Empty file upload result'
  };
</script>

<!-- The template to display files available for upload -->
<script id="template-upload" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
  <tr class="template-upload fade">
    <td class="preview"><span class="fade"></span></td>
      <td class="name"><span>{%=file.name%}</span></td>
        <td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>
        {% if (file.error) { %}
          <td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td>
        {% } else if (o.files.valid && !i) { %}
          <td>
            <div class="progress progress-success progress-striped active"><div class="bar" style="width:0%;"></div></div>
            </td>
            <td class="start">{% if (!o.options.autoUpload) { %}
              <button class="btn btn-primary">
                <i class="icon-upload icon-white"></i>
                  <span>{%=locale.fileupload.start%}</span>
                </button>
            {% } %}</td>
        {% } else { %}
          <td colspan="2"></td>
        {% } %}
        <td class="cancel">{% if (!i) { %}
          <button class="btn btn-warning">
            <i class="icon-ban-circle icon-white"></i>
              <span>{%=locale.fileupload.cancel%}</span>
            </button>
        {% } %}</td>
    </tr>
{% } %}
</script>
<!-- The template to display files available for download -->
<script id="template-download" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
  <tr class="template-download fade">
    {% if (file.error) { %}
      <td></td>
        <td class="name"><span>{%=file.name%}</span></td>
          <td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>
            <td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td>
        {% } else { %}
          <td class="preview">{% if (file.thumbnail_url) { %}
            <a href="{%=file.url%}" title="{%=file.name%}" rel="gallery" download="{%=file.name%}"><img src="{%=file.thumbnail_url%}"></a>
            {% } %}</td>
            <td class="name">
              <a href="{%=file.url%}" title="{%=file.name%}" rel="{%=file.thumbnail_url&&'gallery'%}" download="{%=file.name%}">{%=file.name%}</a>
            </td>
            <td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>
            <td colspan="2"></td>
        {% } %}
        <td class="delete">
          <button class="btn btn-danger" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}">
            <i class="icon-trash icon-white"></i>
              <span>{%=locale.fileupload.destroy%}</span>
            </button>
            <input type="checkbox" name="delete" value="1">
        </td>
    </tr>
{% } %}
</script>

And the javascript:

$(function () {  
  // Initialize the jQuery File Upload widget:
  $('#fileupload').fileupload({
  completed: function(e, data) {
     console.log(data.result[0].picture_id); 
     $("#post_picture_ids").val(function(i,val) { 
          return val + (val ? ', ' : '') + data.result[0].picture_id;
     });
   }
 });

 // Load existing files:
 $.getJSON($('#fileupload').prop('action'), function (files) {
  var fu = $('#fileupload').data('fileupload'), 
  template;
  fu._adjustMaxNumberOfFiles(-files.length);
  template = fu._renderDownload(files)
  .appendTo($('#fileupload .files'));
  // Force reflow:
  fu._reflow = fu._transition && template.length &&
  template[0].offsetWidth;
  template.addClass('in');
 $('#loading').remove();
 });
}); 

Any help with this would be appreciated.

EDIT2: For one solution see below under @SybariteManoj answer. Another solution is to use:

$.getJSON($('#fileupload').prop('action') + '/' + $('#current_post_id').val(), function (files) {

in the beginning of the get function and then add a route for the pictures controller as follows:

get 'pictures/:id', to: 'pictures#index'

The index action in the pictures controller will then filter for the id parameter in this solution and looks like this:

def index
  @pictures = Picture.where(:post_id => params[:id])
  render :json => @pictures.collect { |p| p.to_jq_upload }.to_json
end 

I think I prefer the full solution of @SybariteManoj so there is no need for a route and the index action loks like this now.

def index
  @pictures = Picture.where(:post_id => params[:post_id])
  render :json => @pictures.collect { |p| p.to_jq_upload }.to_json
end 
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T19:17:33+00:00Added an answer on June 18, 2026 at 7:17 pm

    I think I got the culprit. In your javascript, $.getJSON($('#fileupload').prop('action') this is passing the value of the action attribute of the image upload form.

    Try adding this line somewhere in your edit view file

    <%= hidden_field_tag :current_post_id, @post.id, :id => 'current_post_id' %>
    

    and replace this line

    $.getJSON($('#fileupload').prop('action'), function (files) {
    

    with

    $.getJSON($('#fileupload').prop('action') + '?post_id=' + $('#current_post_id').val(), function (files) {
    

    I haven’t tested it but I am quite sure this should solve your issue.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a Rails simple application that has two main models. A person model
I have two models/tables in my Rails application: discussions and comments. Each discussion has_many
I have two models in my rails application. One is User that I have
In my rails application I have two models called Kases and Notes. They work
In rails application I have two models: Food and Drink . Both food and
I have two models defined in Ember and also in a Rails application: App.Library
My rails application has two models, gallery and photo. Galleries have many photos and
I have two models in my rails application Class Employee belongs_to :cost_center End Class
I have a rails app that has two models one is vender and the
So I have a rails application that has two different navigation headers. One that

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.