Rails has_many ajax - ruby-on-rails

Lets say I have a recipe that has_many ingredients, I want the recipe creating page to have forms for each ingredient. How can I make it where a user can click a button to add a new ingredient then save all the ingredients and make them belong to the recipe?

The main idea here is to have a link on your recipe creation page that says something like "Add Ingredient" and give it a unique class. Then use jQuery to add an AJAX action to the click method of those links that will get the page used to create an ingredient. When you you hit Submit, it will come in the params as well. You may have to fiddle around with the IDs of stuff in order to make the the params hash work out nicer.
Let me know if that's enough to get you going or if you want some code examples too.

You're going to want to use accepts nested attributes and build. See Ryan Bates Railscast and just add ajax to it.
Here
And Here

Related

Rails 5 Dynamically Load Nested Form

I'm working on a basic Rails app that currently has two models, Payperiod and Expense. A Payperiod has many Expenses, and an expense belongs to one Payperiod. I have my expenses resourced nested under payperiods, like so:
resources :payperiods do
resources :expenses
end
I am attempting to create an expense on the Payperiod show page. Ideally, I'd like to have a button for adding individual expenses. This is turning out to be trickier than I thought it would be. I know I need to use ajax to dynamically add the form for each expense and submit it but I can't figure out exactly how to make it work. In my Payperiod show.html.erb page I have a button with an id that I can click and make an action happen via jquery. My next step is to make this button render a form. I'm not sure if I can do this via jquery inside of an html.erb file, or if I should convert my payperiod show view to be show.js.erb.

Rails 4 new form defaults from params

I am using form_for in the _form.html.erb view in order to create my form for both the edit and new actions, as per a standard scaffold.
I have a model Owner which has_many pets.
I would like to put an html link on my views/owners/show.html.erb to create a new pet for said owner. This link will point to the new action of pets_controller.rb which when accessed will render the view in pets/new.html.erb
What I want to happen is for the the owner_id to be passed with the link in the url to the new action of pets_controller.rb and then be used as the default for a collection_select in pets/new.html.erb
So I have a link to create a new pet but because that link was on a specific owner page, I want the form to create a new pet to have that owner already set, so the user does not have to select from the list.
This has to be done without changing the behaviour of the edit action/view in pets.
I know that I can pass GET arguments then access them in the controller via params, then create variables in the action which are passed to the view. I can then manually check for a default and set it in the view. I do not need assistance in coding if this is the only solution.
Is there is a better way to do this? A format with which I can pass the params such that the view will just pick them up? Without manually editing my controllers and views?
While my personal inclination would be to do as you said and pass a parameter in the link helper and then access the params array in the pets view, you may find that this is the perfect opportunity to explore Nested Resources. Essentially, you could declare owners/:owner_id/pets/:pet_id route with:
resources :owners do
resources :pets
end
You could then link to this route, and reference :owner_id without having to append the query string to the URI (making somewhat cleaner for reuse).
This is likely more work for you, but also potentially more extensible (and certainly more inline with the Rails way of doing things).
REVISION
Added the following regarding link helpers to the comments, but wanted to reflect it in the answer as well.
To show a pet should be:
<%= link_to owner_pet_path( owner_variable, pet_variable) %>
To view pets' index index should be:
<%= link_to owner_pet_path( owner_variable ) %>
The answer given to this question is fantastic.
As #ConnorCMcKee suggests it would be wise to consider nesting your routes. However, if you are a beginner as myself I found that it helped my learning to simply nest my second controller into the first (i.e. nest PetsController into OwnersController) as a first step. Then afterwards I would continue with the routes.
The method would be something like:
1./ In owners/index.html.erb:
Links to PetsController index action
The key to make this work is to send the :owner_id in your link parameters. Then that Pets index action will have access to that :owner_id and know which :owner_id called it.
2./ In PetsController you would then be able to find that Owner using that id, like so:
params[:owner_id]
Then your actions can start to take advantage of knowing what Owner called them. Remember though that all your redirects inside your PetsController need to preserve params[:owner_id]. That is because once you are inside that nested structure you have to maintain it and stay inside it and always know which :owner_id you are working with.

Rails - Create multiple resources from javascript/coffeescript datas

Suppose I've a model : Thing
class Thing < ActiveRecord::Base
attr_accessible :name, :url
In my coffeescript, I've a function generating an array of JSON objects, eg:
[{"url":"https://www.example.com/1","name":"1"},
{"url":"https://www.example.com/2","name":"2"},
{"url":"https://www.example.com/3","name":"3"}]
That function is called when the user click on a button in the index page of Thing.
What I want is create multiple Thing resources based on the JSON objects generated by the coffeescript function.
What is the best way to do it?
I'm considering using Ajax to redirect to the create action of Thing but not sure this is the best way.
Thanks
Yes, AJAX is the way to go. What you'd do is submit these objects to the controller where you'd make your Thing models.
If you're submitting all of those objects and once and want them all created in one shot you could do that in the create action or you could do that in a create_all action. I like the idea of a create_all action because it's letting us know it's not a simple create action where people have learned to assume it just makes 1 of an object. This is a personal preference though.

Rails MVC: Should a form collection_select know which collection records it should render?

I'm a little stuck here with a conceptual issue. Assume following [abstracted] setup for Post, Tag, and User:
Post belongs_to Tag
Tag has_many Posts
User has_many Tags,
has_many Posts
A user can only tag a post with one of his associated tags.
In the new post form view, I now have following options for selecting a tag:
f.collection_select :tag_id, current_user.tags, ...
f.collection_select :tag_id, #tags, and in the controller's new action:
#tags = current_user.tags
Question: What is the conceptually correct option?
From an MVC perspective, I definitely tend towards using the second option. It does not seem right that the view knows that the tags it should render in the collection_select are associated to a user (even more specific, the current user!).
However, in the official api documentation for collection_select and some other tutorials around the web I see something like this:
collection_select(:post, :author_id, Author.all, ...)
which clearly favors the first option. On the pro-site of this approach, I do not need to redefine the #tags in the create action of the controller in case the post's save action fails and I want to render the new action again.
Thank you for your suggestions in advance.
There's nothing wrong with your first option. For starters, it's simpler (one less line of code). Setting an extra instance variable within your controller doesn't really gain you anything.
A good way of thinking about the controller is that it should only be doing things like setting variables when they are based directly upon input that only the controller receives (such as parameters in the URL, query string, or data from a POSTed form).
The view in this case isn't deciding how to determine the current user - that's still coming from your controller (although probably inherited from the top-level ApplicationController or something like Devise?), all it's doing is deciding that it's the tags of the current user which should be be selectable within the drop-down view.
Does that help?

Rails show view of one model with form for adding one child - nested attributes vs seperate controller vs?

I have a basic two tiered model structure: Articles -> Comments with one Article having many comments.
What is the best way to add a "Add a comment" form to the bottom of the Articles show page?
nested_attributes is overkill as I don't want to be able to edit all of the comments on the page, just to add one more.
Is the best way even with Rails 2.3 still to make a separate controller and embed a form_for pointing to the other controller into the Articles show view? If so, how do I get validation errors to return to the article display page?
I don't want to make a separate comment page/view...
thanks
Lay some code out SWR, and this will also help!
http://railscasts.com/episodes/196-nested-model-form-part-1

Resources