Home > ruby on rails 4 > Creating Instance of Nested model inside parent controller

Creating Instance of Nested model inside parent controller

January 18Hits:1

I would like to know if it is possible to create an instance of a nested model inside the parents controller.

Let me explain. I have a model called Museum and another model called Museumimage. Museumimage has only one field which is an attachment, managed by the Paperclip gem. I have created a separate model for this because there can be as many images as desired linked to the Museum model. I thought this would be better than creating, lets say, 20 attachment fields for the Museum model... Most of it being empty..

Then in the NEW view, I have a form allowing to both adding the information for the Museum instance and somes file fields too.

Here is my view important bits :

<%= form_for :museum, url: museums_path do |f| %> <p>   <%= f.label :name %><br>   <%= f.text_field :name %>    </p> .... <%= f.file_field :image %><br> 

(some params such as :name belongs to the Museum model, and :image to the second nested model Museumimage)

I did a pretty straightforward controller, with the CREATE important bits being :

@museum = Museum.new(museum_params) @museum.save @image = @museum.museumimages.create(image_params) redirect_to @museum 

(for one image at the moment)

Though I get error : ActionController::ParameterMissing in MuseumsController#create

This is my first attempt at Paperclip as well.

My questions :

  • Is it possible to create an instance on a nested model inside parents controller ?
  • if this is possible I guess my code has flaws. Intuitively I think my form helper should make a reference to the nested model :museumimage too ?


I have found a beginning of a solution with the form helpers FIELDS_FOR.

<%= f.fields_for :museumimages do |museumimages_fields| %>   Image: <%= museumimages_fields.file_field :image %>     <% end  %> 

But I still get the error message param is missing or the value is empty: museumimages

app/controllers/museums_controller.rb:191:in `image_params' app/controllers/museums_controller.rb:129:in `create'  "museumimages"=>{"image"=>#<ActionDispatch::Http::UploadedFile:[email protected]=#<Tempfile:C:/Users/Maxence/AppData/Local/Temp/RackMultipart20160118-8768-obyvra.JPG>, @original_filename="DSC07825.JPG", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"museum[museumimages][image]\"; filename=\"DSC07825.JPG\"\r\nContent-Type: image/jpeg\r\n">}}, 

I think my controller bits are not correct.

Def Create  ... @image = @museum.museumimages.new(image_params) @image.save end  def image_params params.require(:museumimages).permit(:image) end 


You need to take a look to accept nested attributes method, this way the model will allow the instance to be saved, then in the method image_params you will need to add an extra param in array form, in this case params.require(:museum).permit(:name, museumimages: [:image])

and that should do the trick

Related Articles

  • Creating Instance of Nested model inside parent controllerJanuary 18

    I would like to know if it is possible to create an instance of a nested model inside the parents controller. Let me explain. I have a model called Museum and another model called Museumimage. Museumimage has only one field which is an attachment, ma

  • Rails - Create instance of a model from within another modelJanuary 18

    I have an application I'm building where I need one model to create instances of another model. I want every Car to have 4 tires. Car model class Car < ActiveRecord::Base has_many :tires after_create :make_tires def make_tires 4.times { Tire.create(c

  • PHP MVC class with controller and nested model

    PHP MVC class with controller and nested modelNovember 26

    I had asked a first question about this class a while ago and got a few answers here which made me rewrite it completely. I removed all statics and globals, added my variables as arguments for the constructor, and pass them again as reference through

  • Problem validating parent model with nested models in modelbuilder

    Problem validating parent model with nested models in modelbuilderMarch 24

    I have a parent model with several nested models. I'm having trouble getting the parent model to validate. The issue is with sub model 4. The two screenshots are of the parent model and sub model 4. The output from sub model 3 feeds into parameter "M

  • How to pass an object from a nested directive with isolated scope to parent controller scope in angularJanuary 19

    I have a directive treeview which contains a nested directive (being the branches) of each item rendered. In the scope of both directives I have declared two parameters that should be talking to the parent controller. filter: '&' //binds the method f

  • model association or controller?November 4

    I'm trying to create a rails app that allows users to submit information about their pets. I've come to a point where my knowledge is limited and I don't know enough about what/how this could be done so I'm hoping this will be relatively easy to answ

  • this.model inside directives in angularJanuary 14

    I have a doubt about how to consult models of controllers in Angular using this.model If I have the next controller: angular .module("myApp", []) .controller('myCtrl', myCtrl) .directive('myDirective', myDirective); function myCtrl(){ var vm = t

  • Codeigniter Fail to Call a Function inside a ControllerJanuary 21

    Thanks a lot for answering my question before So I have another problem in my Codeigniter, it's still the same project, just counting data rows in my database. What I would like to do is creating a function in a Controller, and then call that functio

  • Knockout JS Mapping fromJS nested modelsJanuary 27

    I am having trouble understanding how to work with Knockout JS Mapping Plugin. I have some nested models (as seen below) and what I am currently doing is just using the ko.mapping.fromJS() in the parent model. What I am noticing is that computed valu

  • Rails - Why does my nested model form not require 'accepts_nested_attributes_for'February 9

    I have two models item and user_item. Item has many user_items and user_items belongs to item. I have a form where a user can create a new item. In the form a user should include a picture. The name, description, and tags get saved to a new item obje

  • should I extend or create instance of the classNovember 26

    I have two classes Class A and Class B in Class A, i have three methods that perform the save, delete and select operation based upon the object I pass them. in Class B I perform the logic operations, such as modification to the property of the objec

  • MVC - Checking data in the model or the controller?April 29

    I'm currently creating a web application with Ruby on Rails and I'm facing an conceptual problem about the MVC pattern. If I need to check, for example, if the name of a data that I want to add in the database exists in a given an array, where do I n

  • Updating ngModel of custom element from inside angular controller instead of Angular directiveJanuary 29

    I have a directive something like the following for a custom control myApp.directive('myControl', function ($filter) { return { restrict: 'E', scope: { ngModel: "=" }, templateUrl: 'some template path', controller: 'myControlController' } }); I

  • How to reference the child scope from the parent controller?January 30

    The following code simply displays a form and saves the input with a editDownload method: JS: $scope.editDownload = function(downloadId) { var Download = Parse.Object.extend('Download') var download = new Download() var data = { 'title': $scope.downl

  • Grails injected Mail Service bean is null inside a controller

    Grails injected Mail Service bean is null inside a controllerFebruary 1

    I am trying to use the following Grails Mail plugin: https://grails.org/plugin/mail I've added the depedency in BuildConfig.groovy: plugins { //mail plugin compile "org.grails.plugins:mail:1.0.7" } The I've configured it to use a specific email

  • How to call function in parent controller from directiveFebruary 2

    I have angular controller and its been split down into a directive. Inside that directive the original code is attempting to call a function which still resides in the parent controller but it is claiming its not defined so Im assuming theres an issu

  • How to completely decouple Model from View/Controller in Java SwingJuly 14

    Is there a collection of commonly-agreed-upon design guidelines for separating the Model classes from the View/Controller classes in a Java Swing app? I'm not so concerned that the View/Controller know nothing about the Model as the other way around:

  • Users creating instances from a template - is there a software pattern that corresponds to this use case?February 28

    I am looking into designing a system where users build a template item and then create many instances based on this template.They then need to be able customise each instance but I also need for them to be able to make changes to the template and hav

  • Declaring an instance of class included in parent theme from child theme functions.phpOctober 28

    Please note this is all "working" - the question is about the best practice and to try and work out why I need to include the PHP file which contains the class in two places for it to work correctly. I'm working on a simple parent theme to speed

  • calling method of parent controller from a directive in AngularJSApril 13

    Following my previous question, I'm now trying to call a method on the parent controller from my directive. I get an undefined parameter. Here's what I do: <body ng-app="myApp" ng-controller="MainCtrl"> <span>{{mandat.rum}}

Copyright (C) 2017 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.835 s.