I am trying to implement a nested form for a Book object which can have several BookAuthor objects. I have followed this tutorial to do this with the Cocoon gem in Rails 6, however it does not work. The form itself works well on the front end, adding and removing the BookAuthor fields properly. The params that the server receives contain the correct number of BookAuthor attributes but these sub-objects do not get written to the database, even though the main Book object does. I have been able to get the association to work properly.
There is no error output from either the javascript or rails consoles.
Notes: Ignore the include Hashid::Rails in book.rb, I have tried both with and without this and the same thing occurs. Also, ignore any references to Chapter objects in book.rb, as these are not part of the form yet.
Below is the code for the relevant models, views and controllers. The model files also contain the table schema for that model. If there is any more code you require, please let me know.
Params the server receives (from the server console): https://pastebin.com/nxAXkD3T
book.rb: https://pastebin.com/Xtxf52eT
book_author.rb: https://pastebin.com/miFhb5wR
_form.html.haml: https://pastebin.com/YaW1gRUe
_book_author_fields.haml: https://pastebin.com/FJw7CR2f
books_controller.rb: https://pastebin.com/0NYsCc7x
application.js: https://pastebin.com/rZLpe0iS
Gemfile: https://pastebin.com/TcGrQ9f5
Gemfile.lock: https://pastebin.com/apCMxNkJ
package.json: https://pastebin.com/9U7mB2NK
yarn.lock: https://pastebin.com/H3AzG3Bi
There is no need to add the attr_accessor :book_authors_attributes. in your book.rb. remove it.
This is automatically added with some rails magic.
Related
I'm using the active_model_serializers gem for a RoR API. Versions:
Rails: 4.2.8
Ruby: 2.2.5
active_model_serializers: 0.10.0
I'm using a virtual attribute in a serializer. I get it by using a sub query when I retrieve the objects from the database.
You can find the code here: Github Gist
This is the error I'm getting:
undefined method 'number_of_reservations' for DiscountSchedule...
This field isn't defined in the table nor in the model (attr_accessor)
I'm not sure why it doesn't work, I have a very similar serializer and it's working OK.
Any help will be appreciated.
EDIT:
I have another serializer where the virtual/calculated field is working OK. My guess on this is that since AR is making a bunch of LEFT OUTER JOINS and the SELECT list of the query is very big at some point something is getting broke.
The link won't work for me as I don't have access at my work place, however, from the error I can recommend you to check if you have defined the attributes like this in your serializer attributes :number_of_reservations and have an action in the serializer that says
def number_of_reservations
// Your logic goes here.
end
I suspect this question has to be about ActiveRecord, rather than AMS. You're trying to use select and alias to collect some computed (aggregate) attribute along with objects themselves. This, unfortunately, won't work in ActiveRecord, at least not in versions below 4.2.X. And this is why you're observing this behavior, there is no number_of_reservations in your models.
To see what's going on, try to inspect #objects here: https://gist.github.com/LuisDeHaro/ebf92781b449aa1ee7b85f8f552dd672#file-some_controller-rb-L17
Indeed: the issue was by the big amount of LEFT JOINS that the includes(:table_name) is generating. The serializer then does not know what to do.
I found a monkey-patch gem that works for AR (Rails 4 & 5) that fix this.
https://github.com/alekseyl/rails_select_on_includes
So, the virtual field number_of_reservations is picked up by the serializer like a charm.
And, you might be wondering: why do you want to retrieve a field that is not in the table definition in the database. A: well, in some scenarios you will need a calculated field for EVERY row you are retrieving. A SQL sub query is one of the most efficient ways to do so.
It's working now for me.
This is closely related to Rails ignores columns from second table when using .select, however that question doesn't go deep enough.
As per the above question, I have a complex query being run from one of my ActiveRecord Models which generates a kind of 'report'. It is basically a giant table of the primary Model's attributes as well as a few other attributes from related tables.
The query itself, works. I have verified that the resulting SQL executes correctly and when pasted into a SQL terminal I get the results (and columns I want). Unfortunately there is proprietary information in the models that I can't share here, and the Query is too complex to obfuscate. But To give an idea of what I am doing, this is the start of my ActiveRecord Query: permits = Permit.select('*').joins("LEFT JOIN crosstab (' ....
I have pasted the ActiveRecord Query (above) into the Rails console and not only does it execute perfectly; but the additional attributes (not asssigned to any model or association in my app) can be queried, just fine - exactly what I want:
>> permits.first.applicant_name
"Gordon Ramsay"
The problem is that when I execute the code in the rails app (executed from the browser) I can access the attributes of each permit and its associated models ok, but the additional selects on permit raise a NoMethodError.
I cannot understand why the Rails console will let me plug the commands in and work, but when I run the same code in only of my application's methods, it raises an error.
The question above seems to deal with this closely, and the accepted answer suggests trying something out in the console; but why would the console and the Rails app itself deal with this same code differently (since I am under the assumption that the Rails console is an instance of the Rails application?
Does anyone know:
Is my assumption about the ActiveRecordRelation omitting the non-model attributes correct?
Why does the Rails console allow me to do this query and call the 'extra' selected columns but Rails will not.
Is there a way I can do what I need to do - perhaps creating a proxy object or casting the Permit model to some other ActiveRecord Object that doesn't 'ignore/drop' the extra attributes from the select?
Having the following associations:
Workout has_many workout_sets through ...
workout_set has_many workout_steps through ...
When editing an object I'm experiencing the following issue:
1) go to /model/:id/edit
2) checking the db, once the page loads the top level attributes (the non-nested ones) are deleted from the db once the page loads, but the select marks as selected the correct values, as if in the moment of the load the data was correct.
3) leaving the page without saving (returning to /model/:id) does the following:
3.1) don't update the object, due to no form is submitted.
3.2) leave me with a model without it's primary properties, while the deepest nested attributes remain unchanged.
I'm using cocoon and simple_form to handle nested models. Is it something on Rails I'm missing out?
P.S: I can provide code if needed.
For the record:
The solution is as simple as:
:force_non_association_create => true on each link_to_add_association. For more information check this
Fairly new with rails and am digging with a new web app. I'm parsing an XML file uploaded by the user. The parsing is done with a before_save call in the upload.rb model file.
In the xml parsing function (parse_xml), my intention is to create a new model for the XML children elements and save all the attributes.
The problem I am facing is this:
As I understand, current_user is a controller helper function from devise and is not available in the models. The current model I have (Items Model containing the XML child elements) is tagged against a user_id (The current_user). The Items model does not have controllers at the moment and there is no way I can think of passing in the current_user's ID attribute into the Uploads model.
Again, to my understanding, the Uploads model works on the parse_xml function before actually running the #upload.save function in the uploads_controller.rb.
I'm not sure how to approach this problem. While I know Thread.current[:user] is suggested by a lot of people, as a learner, i prefer getting the right approach in my head rather than have a #facepalm moment when someone looks at my code :-)
Update:
Since Items records require an upload_id value, the records cannot be created until the Parent Upload record is created. Is this the reason why I also get an uninitialized constant Upload::Item error during the before_save execution in Upload#create route?
I'm not sure where things are going wrong!
everyone. So, I'm working on a basic Rails 4 application for practice, and I have a model for FriendCircle and a model for FriendCircleMembership. (the FriendCircleMembership's corresponding table is basically a join table).
In the console, I'm able to create a new FriendCircle object while passing in :friend_circle_memberships_attributes. This successfully inserts a new FriendCircle row into my table as well as inserting the proper rows into the FriendCircleMembership table.
The WEIRD thing is that, even if i comment out that the FriendCircle accepts_nested_attributes for :friend_circle_memberships, it still works. Is this because i am whitelisting it as a permission in the controller?
The other issue is that, even though i can successfully make the nested objects via the rails console, when i try making it through my html form it says my friend_circle_memberships_attributes is an unpermitted parameter. Not sure why this is happening. I check the incoming parameters and they look fine.
any help would be SWEEEEET. thanks.
I determined what the error was: One of my controllers for a nested attributes was validating the presence of the id of the controller it was nested under.
I'm assuming the validation occurs before an id is created, which makes sense, but im not 100%. So i just took out the validator and things worked.