I am an newbie. I have read the API documentation. But still don't understand how form_for works.
Firstly, from Ruby on Rails Tutorial, the form for follow button:
<%= form_for(current_user.relationships.build(followed_id: #user.id)) do |f| %>
<div><%= f.hidden_field :followed_id %></div>
<%= f.submit "Follow", class: "btn btn-large btn-primary" %>
<% end %>
I understand current_user.relationships.build(followed_id: #user.id) means a new record. But why can we not just submit and trigger controller to save the record without hidden_field? Why do we still need to post followed_id to controller?
Secondly, in hidden_field, what does :followed_id means? I believe that is a symbol, i.e. it equals only "followed_id" not a variable of id. If that is only the name of the input field, then what is its value?
Thirdly, how does form_for know where the submission should be sent to? Which controller and action the form_for will post to?
Fourth, how does params work with form_for? In this follow button case, params[:relationship][:followed_id] will return #user.id in controller. How does it know the first hash attribute is :relationship? We have neither mentioned form_for :relationship nor form_for #relationship.
I know these questions can be very dumb, but I am really stuck. Any help will be appreciated.
I didnt do that tutorial so mind me if i dont answer directly to your question.
Take a look at the rails guide about form helpers and it explains in details your questions, probably in a more articulate way than i can.
form_for(path/to/your/controller/action) is a helper method to create HTML form elements with the url path to the POST or GET request. The helper knows if it should be a new record or an update record based on what you are asking to do in your controller action.
For example
In your controller
def new
#my_instance_variable = Myobject.new
end
In your view new.html.erb
<%= form_for #my_instance_variable do |f| %>
...
<% end %>
In your case the logic was directly written in the helper and you could also directly write
<%= form_for Myobject.new %>
Both will result with the following html
<form action="/myobjects/new" method="post">
# in this case rails knows its a `POST` request because the route new action
# is by default a POST request. You can check these routes and their request
# by using `rake routes` in terminal.
Then the hidden_field is another helper to contain a value, in your case the #user.id that will be passed as parameter then saved as a Create or update action for the given object. The reason it doesnt add the value in the hidden field tag is because you already have a model association that knows the id of user since the link of form uses the build method with user id.
Last part you need to understand the form_for link logic
current_user.relationships
# implies the association of the current_user has many relationships
current_user.relationships.build
# .build is a method to populate a new object that can be save as a new record
# means you will create a new relationship record by populating the user_id
# column with the current_user.id and the followed_id with the target #user.id
After reading the book The Rails 4 Way, I understand form_for better now.
11.9.1.5 Displaying Existing Values.
If you were editing an existing instance of Person, that object’s attribute values would have been filled into
the form.
in this way, when we build the relationship by usingcurrent_user.relationships.build(followed_id: #user.id), the relationship instance will be created and gain attribute followed_id. So that, instead of "creating" a relationship, we are actually editing the relationship by the form.
Then Rails will know you are editing and load the existing attribute "followed_id" to the field. Therefore, we don't need to assign value to the field like using f.hidden_field :followed_id, value: #user.id.
And the reason why we have to use a field to pass followed_id to params is because HTTP server is stateless, it doesn't remember you are creating a relationship with which user.
One of the advantages of writing form_for current_user.relationships.build(followed_id: #user.id) instead of standard form_for #relationship is we don't need to write "if-condition" in controller like this:
unless current_user.nil?
if current_user.following?(#user)
#relationship=current_user.relationships.find_by(followed_id: #user.id)
else
#relationship=current_user.relationships.new
end
end
params will be sent to the controller which belongs to the instance's model. "post" method will go to action create, "delete" will go to destroy, "patch" will go to update, etc.
params will be a hash with another hash inside like { instace_name: { field_1: value1, field_2:value2 } } or full params as below
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"afl+6u3J/2meoHtve69q+tD9gPc3/QUsHCqPh85Z4WU=",
"person"=>{"first_name"=>"William", "last_name"=>"Smith"},
"commit"=>"Create"}
Related
<%= form_for [#blog,#blog.comments.build] do |f| %>
<p><%= f.text_area :text, :size => '40x10' %> </p>
<p><%= f.submit "Post Comment" %> </p>
<% end %>
This is handler by comments_controller, but I would like to know the reason, especially for form_for
The form_for creates a form for creation or update of passed object. If the object is not persisted, the associated url will target the creation action. Otherwise the targeted action will the update. form_for can receive many different kinds of parameter to generate the form.
If you check out the Rails url_helpers documentation, you will see that you can do something like:
<%= link_to 'First comment', blog_comment_path([#blog, #blog.comments.first]) %>
This will generate a link to the first comment of the blog with a path like /posts/#post.id/comments/#post.comments.first.id. This also assumes that you have the correct setup on your routes.rb:
resources :blogs do
resources :comments
end
With this, you generate a bunch of paths that you can use to build, for instance, links and forms. Thus, the form_for in your code works similarly. Think of it as a url_helper. You have a #blog and a comment associated to the post(#blog.comments.build). As the comment is not persisted yet, the will generate a form for the creation of comments targetting CommentsController#create. The associated path will be something like /blogs/#blog.id/comments and the HTTP method will be POST.
Also, check these links to get more info:
Rails Routing
Rails Form Helpers
It adds a form with a text box, submit button and some hidden authentication related hidden fields for entering comment.
The comment is added to #blog object with relationship:
has_many :comments
Comment is build by the code if not present by:
#blog.comments.build
So overall you get a form for entering comments in a # blog object. The blog object is necessary in this case and the comment will be automatically combined to the blog entry in proper column in comment record column "blog_id" by default.
This is called Nested Form Relationship, where instead of editing only one record of comment you can combine the parent object also and edit it.
build is basically used to create a structure for object, something like new ( e.g. Model.new). Form action is decided on the basis of given objects. In your case the objects are #blog and #blog.comments.build so the action called will be of either update of Blog controller or Create of Comments Controller..
Hope this helps.
I know I've written it wrong, but I'm looking at the documentation and can't figure out how.
My model is Quote and has three fields, body, attribution, and work, all strings. The form is intended to add a new quote to a page of quotations.
on main/index.html.erb
<%= form_for(:quote, url: {action: 'create'}) do |f| %>
<%= f.text_field :body %>
<%= f.text_field :attribution %>
<%= f.text_field :work %>
<%= submit_tag "Submit" %>
<% end %>
in main_controller.rb
def create
Quote.create(body: params[:body], attribution: params[:attribution], work: params[:work])
end
The form submits, and an entry is saved to the database -- but it's a totally blank entry. I'm not sure why. Help would be appreciated!
Three things:
The way rails forms are supposed to work, you're not meant to get body, attribution, etc independently, they should be wrapped up into a quote object. But...
In your form, your not properly binding an object to the form the way rails expects. You can read more in the documentation here: http://guides.rubyonrails.org/form_helpers.html#binding-a-form-to-an-object. You could also generate a fake scaffold rails generate scaffold HighScore game:string score:integer to generate a fake model and see an example of how it's supposed to work. The default scaffolding even has simple examples of how to deal with save errors.
Finally, as #Paven suggested, when you get confused, be sure to look at what's going on in your log - i.e. what params are being posted to your create action. That is always helpful and a good way to diagnose problems quickly.
Your form does't need the action argument. The form_for helper uses ActiveRecord objects to determine the path, meaning as long as you build your object correctly, you won't need to determine your path individually:
<%= form_for #quote do |f| %>
Secondly, you'll want to look at your create method:
#app/controllers/quotes_controller.rb
def new
#quote = Quote.new
end
def create
#quote = Quote.new(quote_params)
end
private
def quote_params
params.require(:quote).permit(:body, :attribution, :work)
end
The problem is you're not sending an ActiveRecord object to your form_for helper. You can read the explanation here:
In Rails, this is usually achieved by creating the form using form_for
and a number of related helper methods. form_for generates an
appropriate form tag and yields a form builder object that knows the
model the form is about. Input fields are created by calling methods
defined on the form builder, which means they are able to generate the
appropriate names and default values corresponding to the model
attributes, as well as convenient IDs, etc. Conventions in the
generated field names allow controllers to receive form data nicely
structured in params with no effort on your side.
In order to get the form working correctly, you need to be able to provide a valid ActiveRecord object (#variable), which the helper can use to determine the url etc
My code above helps you provide a new ActiveRecord variable, and allows you to use it in the form. This should allow the form_for method to send your data to the create method, which will then create & save an object in the db for you
I have a situation in which I'm passing additional fields to form_for function, which don't belong to a model. Those fields are: redirect_to, redirect_time. I use those fields to know where to redirect the user after the form is successfully submitted - I don't store them, just read in the controller.
Now, everything is working perfectly when I have:
<%= form_for #mymodel .. %>
<%= if defined?(redirect_to) %>
<%= hidden_field_tag :redirect_to, redirect_to %>
<% end %>
<% end %>
And read in controller:
def action
if params['redirect_to']
redirect_to params['redirect_to']
end
end
But the problem occurs when the form has an error, Rails of course, won't pass those params that don't belong to the current resource.
Whats the most elegant way to deal with this situation in Rails to preserve those fields when form submission fails?
Thanks for help
I think you'd be better off storing these variables within the session rather than the form. Firstly it will make them much harder to interfere with if people started poking about in the source of your web page, and secondly they'll be available to whatever action or controller you need them in once you're done with processing the submitted form.
Since they're not related to the form itself it feels much cleaner abstracting them outside of it.
Just set the session variables you need in the controller prior to rendering the form:
session[:redirect_to] = url_to_redirect_to_after_submitting_form
Then you can redirect there after saving the record in your create action:
def create
# ... save record
redirect_to session[:redirect_to]
end
Passing non-model fields through ActiveRecord is poor solution to your problem of routing.
Keep to convention and use ActiveRecord as an interface to the state of your application data.
When I create a form using simple_form_for #model, upon submit the post params has all the attributes grouped under params[model]. How do I get simple_form to drop this grouping and instead send it directly (under params root)?
<%= simple_form_for #user, do |f| %>
<%= f.input :name %>
<%= f.input :password %>
<%= f.submit %>
Now the name and password attributes would normally be sent under params[:user][:name], params[:user][:password] etc. How do I get simple_form to post these as params[:name], params[:password] etc.?
Thanks!
Ramkumar
ps: In case you are wondering why I need this, the bulk of my app is to serve as an API and I have built a set of methods to validate a request which expect some attributes to be in root. In a rare instance (forgot password), I actually need to present a form and I am looking for a way to use these methods.
you can explicitly define the name for an input by passing input_html to it:
input_html: { name: :name }
(needed this myself for sending an resource to a thirdparty endpoint with redirect to my side which relied on the plain attribute names, but i actually wanted not to built up label and input via the tags ;) )
also see simple form builder impl
Two ways I can think of:
The first is, don't use simple_form to build your form, but do it by hand or with the form_tag and *_tag methods. These will allow you to more closely specify what parameters are used in your form.
If you want to keep simple_form, though, then have it call a different controller action. Refactor the controllers to strip out the logic into a separate method. Something like:
class UsersController
def create_from_api
controller_logic(params)
end
def create_from_form
controller_logic(params[:user])
end
def controller_logic(params)
[actual work happens here]
end
end
I had a general question of what is going on when code like this runs:
<%= form_for(current_user.favorite_relationships.find_by_lesson_id(#lesson),
html: {method: :delete},
remote: true) do |f| %>
<div><%= f.hidden_field :lesson_id %></div>
<%= f.submit "Unfavorite", class: "btn btn-large" %>
<% end %>
specifically the very first line of code. i usually see some form of instance variable instead of
current_user.favorite_relationships.find_by_lesson_id
I can assume that this will go into the FavoriteRelationship controller's destroy action. Is there anything else someone can infer from that form above? Like what will be available or gets passed in the destroy action?
Presumably, the controller has supplied a Lesson object to the view through the variable #lesson. Your current user, a User object, presumably has_many :favorite_relationships, which in turn belongs_to :lesson, meaning there is a field within the favorite_relationships table called lesson_id.
Rails builds "magic" finder methods for your models for the fields it contains. If a model has a lesson_id field, Rails provides a find_by_lesson_id helper. Rails is smart enough to extract #lesson.id when you pass it an actual Lesson object instead of an integer.
The net result is that an object of type FavoriteRelationship is being passed into the form_for helper. This is no different than finding the object in the controller and passing it to the view via a (for example) #favorite_relationship variable.
what will be available or gets passed in the destroy action?
The only thing available to the controller on the subsequent request to the FavoriteRelationship's destroy route is the id of the object to destroy. You'll be able to access it via params[:id].
The destroy action is via AJAX (presence of remote: true)
In general, the main logic/code is refactored into either a controller or a helper method.
The #favorites = current_user.favorite_relationships.find_by_lesson_id(#lesson), IMO, should be placed inside the controller rather than the view and the view should have #favourites in the form_for part. That is the reason for the observation you've made about instance variables