Problem solved. HTML5 localStorage messed with me.
I'm trying to populate a form with parameters from the new()-method, and I can't get it to work.
Every user has default values for the form saved in the database(in a table called defaults), and when you create a new record I want it to be populated with the values from that table.
#default = Default.find_by_user_id(current_user.id)
#invoice = Invoice.new(:title => #default.title, :company_information => #default.company_information)
render 'create'
and then in my view:
form_for #invoice, :url => { :action => "create"} do |f| ...
What happens is that the values that are default for invoice are created, but not the ones created in the new()-method.
The weirdest part is that when I check the source code after the page is loaded, the inputs value attributes is filled with the correct information, but not rendered on the page...
What you're doing here:
Invoice.new(:title => #default.title, :company_information => #default.company_information)
Makes sense and should work…unless those fields are protected from mass assignment.
class Invoice << ActiveRecord::Base
attr_accessible :some, :other, :fields
...
end
This would allow you to set :some, :other, (and) :fields when you initialize your Invoice object, but it will prevent you from setting any other "attributes".
Strange, I don't see anything wrong with what you are trying to do... maybe something on the browser side (javascript, css, etc) is fowling things up?
Check to see if there is something selectable inside the form inputs or try creating a vanilla form without any javascript or css. Or, you might even try simply printing the contents of the attribute in the html (without using input/textarea tags) using something like:
<%= #invoice.title %>
This will at least help confirm that the default values where indeed set. Additionally, using:
<%= f.object.title %> # place me inside the form_for block
will help you confirm that the form builder instance also has the correct value.
Good luck.
Related
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 know views shouldn't be rendered from a model, but I cannot make sense of a better way to handle this problem.
I have a simple_form form that should show a list of object as checkboxes:
= f.association :results, collection: #search.results.all(order: 'cost'), as: :check_boxes
Like this it would only show the object next to a checkbox, but I need to display a bunch of more detailed information, so I'm defining the to_label method in my model like this:
class Result < ActiveRecord::Base
belongs_to :search
def to_label
"<div class='row'>
<div class='col-md-2'>#{supplier}</br><span class='label label-default'>#{brand}</span></div>
<div class='col-md-2'>#{desc}</div>
<div class='col-md-2'>#{model}</div>
<div class='col-md-1'>#{season}</div>
<div class='col-md-1'>#{qty}</div>
<div class='col-md-1'>#{expected_delivery}</div>
<div class='col-md-1'>#{msrp}</div>
<div class='col-md-1'>#{cost}</div>
</div>".html_safe
end
end
This shows some better formatted information, but still it's becoming very complicate to mantain and I will need at some point to add information like images etc. Of course it is also very wrong from a MVC point of view.
My idea is to create a partial in app/views, using haml as for the rest of my application and make my to_label method look like this:
def to_label
render "results/label"
end
Of course rails won't allow me to do that, but I have no better idea on how to implement it.
You should not access views from a model. Instead, create a helper with a function that receives the result object as a parameter (code not tested):
helpers/results_helper.rb
result_to_label(result)
render(:template =>"results/label", :layout => nil , :locals => { :result => result }).to_s
end
Then, from your view you call result_to_label(the_result) directly.
Update
In your simple_form, you can add the label_method with a lambda:
= f.association :results, collection: #search.results.all(order: 'cost'), label_method: lambda { |res| result_to_label(res) }
Bending rails that way will get you somewhere you don't wanna be. First of all you trying to render complex html layout by making simple_form thinking it's label for form control. Building custom form without use of simple_form makes more sense. Because rendering simple controls with automatic label generation is kinda simple form thing. And you are way beyond that.
So solution to your problem as it seems for me is defining to_partial_path on your class:
class Result < ActiveRecord::Base
def to_partial_path
'results/form'
end
end
and render your form with:
= render #results
it may be rendered inside of simple form you just need to build form controls with rails or simple form helpers.
I'm working on a Rails form that will allow the user to edit the attributes of many objects of a class with a single submission. My initial instinct was to create an outer form_for block and then iterate through the items within it using fields_for.
However, there is no object that bears a one-many relation to the objects the form will modify, and so it seems to me that there is no object that would be correct to pass into form_for.
In any case, what I'd like to see is an example of a form that modifies multiple objects simultaneously without appealing to a "parent" object. Perhaps this will involve form_tag?
(Note: I'm working in haml, so answers in haml would be awesome though unnecessary.)
Well, having a parent object will make it easier.
For bulk updates of many objects, the key is to use the right input name so that rails will parse the params as a array, i.e.
#posts.each do |post|
fields_for "posts[#{post.id}]", post do |p|
p.text_field :name
p.hidden_field :id
end
end
Have a look at the generated html source to see what name attribute the text input gets. If this is done right, params[:posts] will now be a hash in the controller which you can then update.
http://railscasts.com/episodes/165-edit-multiple should be relevant too
There are some extra wrinkles to my actual situation, but here's some pseudocode that I hope will illustrate the approach I've taken:
= form_tag url_for(:controller => "the_controller",
:action => "update") do
#objects_to_be_updated.each do |object|
= check_box_tag "[desired_path][through_the][parameters_hash]", true, object.boolean_attibute
= text_field_tag "[another_path][through_the][parameters_hash]", object.text_attribute
end
end
And so on.
Using the _tag variants of the form helpers, which don't require association with an Active Record model, is a bit of a pain but also seems to give you more control over structure of the resulting parameters.
With the following Store and Service models, managed with MongoMapper:
class Store
include MongoMapper::Document
key :service_ids, Array, :typecast => 'ObjectId'
many :services, :in => :service_ids
end
class Service
include MongoMapper::Document
key :name, String
many :stores, :foreign_key => :service_ids
end
I have this form, done with Formtastic:
<%= semantic_form_for #store, :url => admin_store_path(#store), :method => :put do |form| %>
<%= form.input :service_ids, :label => "Select Store Services",
:as => :check_boxes,
:collection => Service.all %>
<% end -%>
The controller uses Inherited Resources, and the edit action is implicit.
When editing a #store with services already associated with it, the checkboxes for the latter don't show as checked.
Formtastic's README warns it doesn't support MongoMapper officially, but it also says people have been using both together successfully, and I've seen some examples of this online.
I suspect Inherited Resources also doesn't support it, from what I've seen from Devise + Simple Form, both from the same authors and which don't support MM. They're working towards using an ORM adapter in their gems, but it isn't ready yet AFAIK.
And I've had problems with it already, I'm overriding the update action to get it to work:
def update
store = Store.find(params[:id])
if store.update_attributes!(params[:store])
flash[:notice] = 'Store was successfully updated.'
redirect_to admin_store_path(store)
else
redirect_to new_store_path
end
end
Does anybody know where the conflict with MM is, either in Formtastic or IR, and a hack just to get these checkboxes checking?
Most likely a Formtastic issue. It looks like the problem is here: https://github.com/justinfrench/formtastic/blob/master/lib/formtastic/inputs/check_boxes_input.rb#L122
Formtastic calls #store.service_ids to find the selected boxes. Service_ids returns an array of ObjectId's, but Formtastic was expecting an array of Store objects. If we follow Formtastic's code we'll see it tries a couple methods to find out how to get the "value" out of those ObjectId's and will eventually settle on "to_s" (see https://github.com/justinfrench/formtastic/blob/master/lib/formtastic/form_builder.rb#L20). Unfortunately, the to_s of an ObjectId is not the same as the id of your Store objects.
A hack that might make it work is to add an "id" method to ObjectId that returns self (Formtastic looks for id before it looks for to_s). A more appropriate patch would be to override this method https://github.com/justinfrench/formtastic/blob/master/lib/formtastic/inputs/base.rb#L104 to properly introspect MongoMapper associations, so that you could write form.input :services and it would turn that into an input with name of "service_ids" while still using the services method of your object. With that change it would still properly call #store.services and find the same kind of objects as Store.all and just work.
If you want to go that route, Store.associations[:services] should get you MongoMapper's definition of the association which you can introspect (see https://github.com/jnunemaker/mongomapper/blob/master/lib/mongo_mapper/plugins/associations/base.rb) but note that associations have been refactored a bit since the 0.8.6 gem, they're now in the separate classes BelongsToAssociation, OneAssociation, and ManyAssociation that each inherit from Associations::Base.
So, it doesn't seem like there's a simple fix. The other option is to generate your checkboxes by hand.
(Aside: I'm a little confused by your update method because I'd expect IR to do exactly what you've written internally, but if you had to write it that way to get it to work, so it is...)
On a Content model have an attribute named slug. When creating a new record, I want to use a helper to populate this field, but on an existing record I want to use the value from the database.
Currently I have:
<% if #content.new_record? %>
<%= f.text_field :slug, :value => "#{generate_slug(6)}" %>
<% else %>
<%= f.text_field :slug %>
<% end %>
But that seems a bit verbose. Is this the best way, or is there no other way? (Rails newb just trying to find the "Rails way" on issues I'm unsure of)
Edit
I should note that the helper is currently in /app/helpers/application_helper.rb Moved to be a private action in the Contents controller. David's answer worked great.
In your controller
#content.slug ||= generate_slug(6)
This will assign a value to the slug attribute if none is present
Then, in your view you can simply use
<%= f.text_field :slug %>
Options
Try after_initialize callback in your model.
Try creating a method in your model where you set defaults and call it in your new action in the controller. Also call this method if your create fails and you render new. Remember to set default only when no value exists by using the ||= operator.
Example to follow. I'm typing on phone!
I happen to use jQuery in my projects, so when I want some functionality like this, I usually use something like labelify. Then, I'd use something like <%= f.text_field :slug, :title => generate_slug(6) %>. (Hot tip, you don't need to put the #generate_slug call inside of a string if it returns something that will resolve to a string by itself, in fact it's more performant if you don't.)
If you don't want to go with jQuery approach, you might want to wrap this piece of logic in your model.
def Content < ActiveRecord::Base
def slug
self.new_record? ? self.slug_for_new_record : attributes[:slug]
end
private
def slug_for_new_record
# I don't know what you're doing in generate_slug, but it sounds model-
# related, so if so, put it here and not in a helper
end
end
If it really belongs in the view, still another option is to just make your Ruby a little bit more concise (you'll have to judge if this is more readable):
<%= f.text_field :slug, :value => (generate_slug(6) if #content.new_record?) %>
Don't forget the parens surrounding (generate_slug(6) if #content.new_record?). If you do, the if will be applied to the text_field, which is not what you want.
But there are still more ways to do it. The above line of code isn't great if your logic might change and you're pasting this code all over your rails project. When I wanted to add a 'required' class to my text fields but only if they were a new record (we had some legacy data that we didn't want to make people clean up), I created my own form builder with a required_field method that just called text_field and added a 'required' class if the item was a new record. This might seem like a work, but we have around 20 different forms, each with potentially multiple required fields, and it's a lot easier to change the business logic in one place. So if you really think this logic belongs in the view but you've got a ton of these lines of code and you don't want to have to change it in a million places, then FormBuilder is the way to go. I think this is in most cases prettier and more appropriate than a helper, but again, beauty is in the eye of the beholder. Here's my code somewhat adapted for your case:
# config/environment.rb
ActionView::Base.default_form_builder = NamespacesAreFun::FormBuilder
# lib/namespaces_are_fun/form_builder.rb
module NamespacesAreFun
class FormBuilder < ActionView::Helpers::FormBuilder
def slug_field(method, options = {})
opts = options.to_options
opts.merge!(:value => generate_slug) if self.object.new_record?
text_field(method, opts)
end
end
end
# views/.../your_view.html.erb
<%= f.slug_field :slug %>
Hopefully in all of these different approaches is one that fits your project.