I'm creating a Rails application, and I've hit a bit of a snag. I want a "create new record for DataType1" form that not only creates a new row for DataType1, but also inserts up to four new rows for DataType2.
I know all about fields_for, but my problem is that I need to submit up to four DataType2s, and the only connection they have to DataType1 is that they are referenced via a field in DataType2.
Here's the simplified database:
create_table :data_type_1 do |t|
t.string :title
t.text :body
t.timestamps
end
create_table :data_type_2 do |t|
t.belongs_to :parent
t.timestamps
end
Now, I have the relationships all set up and everything; that's not the problem. The problem is that I just can't seem to figure out how to pass the params for the DataType2s in with the params for the new DataType1. Once someone shows me how I should go about doing this, I can set up the new DataType2s to associate with the new DataType1 fairly easily.
Here's what I have for the form at the moment:
<% form_for(#data_type_1) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :title %><br />
<%= f.text_field :title %>
</p>
# Etc...
<p>
# New items need to be iterated here
# DataType2[1]: [ ]
# DataType2[2]: [ ]
# DataType2[3]: [ ]
# DataType2[4]: [ ]
# (Note that these numbers are just examples.)
</p>
<p>
<%= f.submit "Create" %>
</p>
<% end %>
I'm relatively new to Rails, and I apologize if this question rambles a bit.
This RailsCast talks about inserting lists of "DataType2" into "DataType1". The interesting parts are these
app/views/projects/_form.html.erb
<% for task in #project.tasks %>
<% fields_for "project[task_attributes][]", task do |task_form| %>
<p>
Task: <%= task_form.text_field :name %>
</p>
<% end %>
<% end %>
app/models/project.rb
def task_attributes=(task_attributes)
task_attributes.each do |attributes|
tasks.build(attributes)
end
end
Related
I have a form to create adverts.
Controllers:
def edit
#engines = Engine.all
#car = Car.find(params[:id])
end
def update
#car = Car.find(params[:id])
if #car.save
redirect_to root_path
end
end
My routes:
resources :adverts
Create.html.erb
<%= form_for #car, :url => adverts_path do |f| %>
<div><%= f.label :name %><br />
<%= f.text_field :name %></div>
<%= hidden_field_tag :model_id, params[:model_id] %>
<%= select_tag :engine_id, options_from_collection_for_select(#engines, "id", "name",:selected=>#car.engine_id) %>
<div><%= f.submit "Create car!" %></div>
<% end %>
I can create advert, but I can't to update it.
edit.html.erb
<%= form_for #car, :url => adverts_path do |f| %>
<div><%= f.label :name %><br />
<%= f.text_field :name %></div>
<%= hidden_field_tag :model_id, params[:model_id] %>
<%= select_tag :engine_id, options_from_collection_for_select(#engines, "id", "name",:selected=>#car.engine_id) %>
<div><%= f.submit "Update car!" %></div>
<% end %>
when I submited my form, I have an error - No route matches [PUT] "/adverts"
$ rake routes:
adverts GET /adverts(.:format) adverts#index
POST /adverts(.:format) adverts#create
new_advert GET /adverts/new(.:format) adverts#new
edit_advert GET /adverts/:id/edit(.:format) adverts#edit
advert GET /adverts/:id(.:format) adverts#show
PUT /adverts/:id(.:format) adverts#update
DELETE /adverts/:id(.:format) adverts#destroy
I need help.
When you are updating you have to let Rails know which object you want to update by passing an id.
In edit.html.erb change:
<%= form_for #car, :url => adverts_path do |f| %>
to:
<%= form_for #car, :url => advert_path(#car) do |f| %>
By the way, I find your code very strange. Why don't your model names match your controllers and routes? I mean you are creating an advert but your model is called car. That doesn't make any sense. Either call it car or advert, but don't mix them.
If you used RESTful routing, you don't need to specify a url, just need:
<%= form_for #car do |f| %>
The form can know #car is new record, or saved record, so it will send appropriate http method.
And in your update action:
def update
#car = Car.find(params[:id])
if #car.update_attributes(params[:car])
redirect_to root_path
end
end
I got myself in a similar situation today with a mismatched resource and model name. I agree the model and controller names need to correlate, but you can override the routes name to be whatever you want.
resources :cars, path: "adverts"
Along with RESTful routing
<%= form_for #car do |f| %>
You may also want to make sure your url: path is singular on the #form_form.
Currently using Rails 3.2 and Carrierwave.
I have multiple files setup, but it requires multiple file fields but I only want one file field. I will provide this as the default if the browser does not support the HTML5 multiple property.
Controller
def new
#ad = Ad.new
5.times { #ad.images.build } // provides multiple file fields in the view.
end
def create
ad = Ad.new(params[:ad])
user = User.find(session[:user_id])
if user.ads << ad
flash[:notice] = "Ad successfully saved."
redirect_to ad_listing_path(ad.id, ad.slug)
else
render :new, :alert => "Ad was not saved."
end
end
View
<%= f.fields_for :images do |a| %>
<% if a.object.new_record? %>
<%= a.file_field :image, :multiple => true %><br>
<% end %>
<% end %>
If 5.times { #ad.images.build } is providing my multiple fields, what is the proper way to display 1 file field that accepts multiple?
This seems to be a popular issue with no good answers, so I'm going to completely answer it here. Before I start I will mention that the code is available at https://github.com/mdchaney/multi, but follow along to see how to do this in the easiest way possible.
Before we go there, in HTML 5 a file input field can have the "multiple" attribute set. If it's set, the result is the same as having multiple file inputs of the same name. In Rails, setting "multiple: true" for the file input field built by the form builder will cause it to upload as an array of files.
<%= f.file_field :files, :multiple => true %>
becomes
<input id="model_files" multiple="multiple" name="model[files][]" type="file" />
where "model" is the name of your model. This input control will (in Chrome, at least) have a label of "Choose Files" instead of "Choose File".
CarrierWave cannot deal with this natively. It uses a single text field to store information about a single file, and some internal logic to determine where that file (and possibly its derivatives) are stored. It would be possible to hack it to put information for multiple files in a single text field, choosing an encoding with a set delimiter. This would require a lot of work and hacking on CarrierWave.
I don't care to hack CarrierWave, though, so the issue turns into the fact that having multiple files attached to one item is actually a one to many relationship, or in Rails terms a "has_many". So it's possible to add the files from the file input field to multiple attached records using a simple attribute writer.
With that, I present the simplest way to do this that uses an HTML 5 file input field with the multiple attribute set. There are ways to do it with jQuery and flash, but I am presenting this to show specifically how to do it with straight HTML 5.
In our sample, we will have a simple model for "uploads", each of which will have a name and any number of linked files, which will be stored in another model called linked_files (making it easy, right?). The linked_file will hold the original filename, provided content type, and of course the field for CarrierWave to store its information.
Let's create the scaffold for uploads and then just the model for linked_files:
rails g scaffold Upload name:string
rails g model LinkedFile upload:references filename:string mime_type:string file:string
With that done, we can set limits if we wish on the fields and add the "not null" constraint:
class CreateUploads < ActiveRecord::Migration
def change
create_table :uploads do |t|
t.string :name, limit: 100, null: false
t.timestamps
end
end
end
class CreateLinkedFiles < ActiveRecord::Migration
def change
create_table :linked_files do |t|
t.references :upload, null: false
t.string :filename, limit: 255, null: false
t.string :mime_type, limit: 255, null: false
t.string :file, limit: 255, null: false
t.timestamps
end
add_index :linked_files, :upload_id
end
end
Now, let's fix up the Upload model by adding a new attribute writer called "files":
class Upload < ActiveRecord::Base
has_many :linked_files, inverse_of: :upload, dependent: :destroy
accepts_nested_attributes_for :linked_files, reject_if: :all_blank, allow_destroy: true
validates_associated :linked_files
attr_accessible :name, :files, :linked_files_attributes
def files=(raw_files)
raw_files.each do |raw_file|
self.linked_files.build({filename: raw_file.original_filename, mime_type: raw_file.content_type, file: raw_file})
end
end
validates :name, presence: true, length: { maximum: 100 }
end
Most of that is the normal declarations for the Rails model. The only real addition here is the "files=" method, which takes a set of uploaded files in an array and creates a "linked_file" for each one.
We need a CarrierWave uploader:
class FileUploader < CarrierWave::Uploader::Base
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{model.id}/#{mounted_as}"
end
end
This is the simplest uploader possible, you may wish to restrict the type of file uploaded or whatever. Now, the LinkedFile model:
class LinkedFile < ActiveRecord::Base
mount_uploader :file, FileUploader
belongs_to :upload, inverse_of: :linked_files
attr_accessible :file, :filename, :mime_type, :file_cache, :remove_file
validates :filename, presence: true, length: { maximum: 255 }
validates :mime_type, presence: true, length: { maximum: 255 }
end
And that has nothing special, only added :file_cache and :remove_file as accessible attributes for the file uploader.
We are now done except for the views. We really only have to change the form, but we'll also change the "show" to allow access to the uploaded files. Here's the _form.html.erb file:
<%= form_for(#upload, { multipart: true }) do |f| %>
<% if #upload.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#upload.errors.count, "error") %> prohibited this upload from being saved:</h2>
<ul>
<% #upload.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<% if f.object.linked_files.size == 0 -%>
<div class="field">
<%= f.label :files %><br />
<%= f.file_field :files, :multiple => true %>
</div>
<% else -%>
<fieldset>
<legend>Linked Files</legend>
<%= f.fields_for :linked_files do |lff| -%>
<div class="field">
<%= lff.label :filename %><br />
<%= lff.text_field :filename %>
</div>
<div class="field">
<%= lff.label :mime_type %><br />
<%= lff.text_field :mime_type %>
</div>
<div class="field">
<%= lff.label :file, 'File (replaces current selection)' %><br />
<%= lff.file_field :file %>
<%= lff.hidden_field :file_cache %>
</div>
<div class="field">
<%= lff.check_box :_destroy %>
Remove this file
</div>
<hr />
<% end -%>
</fieldset>
<% end -%>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
I have added two sections of code. If the #upload object has no "linked_files" associated with it, I simply show the multiple file input. Otherwise, I show each linked_file with all its information. It would be possible to add a "files" method to Upload and handle it that way, but doing so would lose the mime type across requests.
You can easily test this as the upload "name" is a required field. Start a server and go to http://127.0.0.1:3000/uploads to see the application. Click the "new" link, choose some files and hit "Create Upload" without providing a name. The next page will show all of your files now waiting. When you add a name everything is saved. Let's modify the "show" action to show the linked_files:
<p id="notice"><%= notice %></p>
<p>
<b>Name:</b>
<%= #upload.name %>
</p>
<p>
<b>Files:</b><br />
</p>
<table>
<thead><tr><th>Original Filename</th><th>Content Type</th><th>Link</th></tr></thead>
<tbody>
<% #upload.linked_files.each do |linked_file| -%>
<tr>
<td><%= linked_file.filename %></td>
<td><%= linked_file.mime_type %></td>
<td><%= link_to linked_file.file.url, linked_file.file.url %></td>
</tr>
<% end -%>
</tbody>
</table>
<%= link_to 'Edit', edit_upload_path(#upload) %> |
<%= link_to 'Back', uploads_path %>
In this I've simply added a header for "Files" and a table which shows all of them and provides a link for viewing. Nothing fancy, but it works.
If I were making this into a real application I would probably also provide a list of files or minimally a count of files on the uploads index page, also.
So that's it. Again, the entire test app is available at github if you want to download it, but I have put the entirety of my Rails generating statements and changes in this post.
Multiple uploads for one file field isn't really supported by HTML. You can get around it with some JavaScript plugins. Two that come to mind:
Uploadify
jQuery File Upload
Unfortunately, CarrierWave does not support the HTML5 multiple attribute (yet).
https://github.com/carrierwaveuploader/carrierwave/issues/984
I'm trying to create a multi-page form that uses multiple models. I have an applicant and this applicant has more than one address (one to many relationship).
I would like the first page to contain information about the applicant, and then the page after that to have the form for the address(es)
This is what I have at the moment:
applicant.rb
has_many :addresses, :dependent => :destroy
accepts_nested_attributes_for :addresses
address.rb
belongs_to :applicant
applicants_controller.rb:
def new
session[:applicant_params] ||= {}
#applicant = Applicant.new(session[:applicant_params])
2.times do
#addresses=#applicant.addresses.build
end
session[:address_params] = #addresses.attributes
end
def create
session[:applicant_params].deep_merge!(params[:applicant]) if params[:applicant]
session[:address_params] ||= params[:address]
#applicant = Applicant.new( session[:applicant_params] )
#applicant.addresses.new(session[:address_params])
if params[:forward_button] or params[:back_button]
#applicant.current_step = session[:applicant_step]
if params[:back_button]
#applicant.previous_step
else
#applicant.next_step
end
session[:applicant_step]=#applicant.current_step
render "new"
else
.....
In the new view:
<%= form_for #applicant do |f| %>
<%= render "#{#applicant.current_step}_step", :f => f %>
<p><%= f.submit "Continue", :name => "forward_button" unless #applicant.last_step? %> </p>
<p><%= f.submit "Back", :name => "back_button" unless #applicant.first_step? %></p>
<% end %>
#applicant.current_step will be either address_step or applicant_step, and these are below:
_applicant_step.html.erb
<div class="field">
<%= f.label :first_name %><br />
<%= f.text_field :first_name ,:width=>'10px', :size=>"20", :maxlength=>"20" %>
</div>
<div class="field">
<%= f.label :middle_name %><br />
<%= f.text_field :middle_name %>
</div>
....
_address_step.html.erb
<%= f.fields_for :addresses do |u| %>
<div class="field">
<%= u.label :address %><br />
<%= u.text_area :address , :cols=> 20, :rows=>5%>
</div>
<div class="field">
<%= u.label :telephone, "Telephone Number" %><br />
<%= u.text_field :telephone %>
</div>
...
And that's it. Now the problem I have is as follows, I want to save the address information as well as the applicant information. And I thought just by saying: #applicant.addresses.new then they will be included in the session information of the applicant, but they weren't (when I got the the address page, there were no fields!). So I created a new session variable to hold the address information. But I have a problem. Everytime I go from one page to the other (in the create action) a new address field (with all its attributes) is created and added to the form. So first I have one address, then I have 2 and so on. Am I going about this the wrong way? How can I have a multi-page form, with multiple models (that are related), and when going from one page to the next the data is not erased.. Until I eventually reach the last page where I could submit (and save) all the models..
I would be grateful if anyone could help..
Thank you.
You can certainly get this working, but (depending on the number of steps you need), it could get pretty convoluted.
Have you considered using a single new and create request on the server side, and using Javascript to break up the form into multiple steps on the client side? It seems like this could be a lot simpler. Your Rails application will behave more like a standard REST application, and you can break this up however you see fit on the client side.
I have not used it myself, but a jQuery plugin such as this one should do the trick:
http://thecodemine.org/
I have an rails 3 application where there are multiple registrations (diagnosis, patient, laboratory test, service, client, user, supplier). Initially these will be populated by seeding the database. The requirement is for the description codes to be mixed case (capitalised first word) when either
1. specified by the application (some configuration setting - yet to be determined)
2. specified by data entry user
At present I have a model, view & controller for Diagnosis which contains two fields:
1. code (always to be capitalised)
2. description (First word capitalised based on check_box_tag value)
Presently I am using a before_save callback in the model to implement the conversion, but I cannot get it to only work when the check_box_tag is not selected i.e. its ignoring the check_box_tag.
I have tried changing the check_box_tag to a check_box adding an attr_assessor to the model (but not the sqlite3 db as it is not required to be stored).
This didn't work either.
How do I accomplish this? How do I override the option to use a checkbox from an internal application configuration file which results in either the checkbox being 'unavailable' or not visible if the application configuration specifies not user selectable?
Model (diagnosis.rb)
require 'DescriptionHelper'
class Diagnosis < ActiveRecord::Base
attr_accessible :code, description
string_correct_case = DescriptionHelper.new([:code, :description])
validates :code, :presence => true, :length => { :minimum => 4, :maximum => 4 }
validates :description, :presence => true
before_save string_correct_case
end
Callback in DescriptionHelper.rb
class DescriptionHelper
def initialize(attribute)
#attrs_to_manage = attribute
end
def before_save(record)
#attrs_to_manage.each do |attribute|
record.send("#{attribute}=", capitaliseWords(record.send("#{attribute}")))
end
end
private
def capitaliseWords(value)
value = value.mb_chars.downcase.to_s.gsub(/\b\w/) { |first| first.upcase }
end
end
Controller (diagnoses_controller.rb)
class DiagnosesController < ApplicationController
def new
#diagnosis = Diagnosis.new
end
def create
#diagnosis = Diagnosis.new(params[:diagnosis])
if #diagnosis.save
flash[:notice] = "Diagnosis created with params [#{#diagnosis.attributes.inspect}" #for debugging, once fixed will be just 'Diagnosis created.'
redirect_to #diagnosis
else
flash[:alert] = "Diagnosis not created."
render :action => "new"
end
end
.. other controller actions - edit, show, destroy
end
View (_form.html.erb)
<%= form_for(#daignosis) do |f| %>
<div class="field">
<%= f.label :code %>
<%= f.text_field :code %>
</div>
<div class="field">
<%= f.label :description %>
<%= f.text_field :description %>
</div>
<div class="field">
<%= check_box_tag("diagnosis_desc_dont_convert", 1, false) %><%= f.label "Leave as entered" %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
When this runs currently the check_box_tag is ignored.
When adding in the model an attar_assessor :description_correctcase and changing the view to use f.check_box 'description_correctcase' this is still ignored.
How does one get this to work?
Thanks in advance from a rails aspiring developer.
Finally got a solution to the problem, after reading and re-reading various SO solutions to component parts of my question. I'm not sure its correct in terms of rails, but it works.
If you can offer me a better solution I would certainly learn from this.
Here is my solution.
Model (diagnosis.rb)
require 'DescriptionHelper'
class Diagnosis < ActiveRecord::Base
attr_accessor :do_not_correctcase
attr_accessible :code, :description, :do_not_correctcase
before_save DescriptionHelper.new([:code, :description]), :if =>
lambda { |d| d.do_not_correctcase.to_s == '0' }
validates :code, :presence => true, :length => { :minimum => 4, :maximum => 4 }
validates :description, :presence => true
end
This I referenced from the following SO solution - https://stackoverflow.com/a/6388691/1108010
Controller (diagnoses_controller.rb)
class DiagnosesController < ApplicationController
def new
#diagnosis = Diagnosis.new
end
def create
#diagnosis = Diagnosis.new(params[:diagnosis])
#diagnosis.do_not_correctcase = params[:diagnosis][:do_not_correctcase]
logger.debug "New diagnoses: #{#diagnosis.attributes.inspect}"
logger.debug "Diagnosis should be valid: #{#diagnosis.valid?}"
logger.debug "code has value #{params[:code]}"
if #diagnosis.save
flash[:notice] = "Diagnosis created with params [#{#diagnosis.attributes.inspect}" #for debugging
redirect_to #diagnosis
else
flash[:alert] = "Diagnosis not created."
render :action => "new"
end
end
.. other controller actions - edit, show, destroy
end
I also changed the view to replace the check_box_tag with a check_box.
View (_form.html.erb)
<%= form_for(#daignosis) do |f| %>
<div class="field">
<%= f.label :code %>
<%= f.text_field :code %>
</div>
<div class="field">
<%= f.label :description %>
<%= f.text_field :description %>
</div>
<div class="field">
<%= f.check_box 'do_not_correctcase' %><%= f.label "Leave as entered" %><br />
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
So despite getting this to work I'm not clear on are the following:
When inspecting the attributes with "#{#diagnosis.attributes.inspect}".
I assume that the reason the attr_accessor variable is not included in the New diagnosis output is that it is not part of the database table and therefore Active Reocrd does not instanciate it as part of the new record with #diagnosis.new
Could someone be kind enough to confirm that.
Why does the log have no value for logger.debug "code has value #{params[:code]}"? What causes the params[:code] to be null in the logger output?
Logfile contained the following entry:
Started POST "/diagnoses" for 127.0.0.1 at 2012-03-05 09:36:38 +0000
Processing by DiagnosesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"RW/mzkhavGeaIW0hVLn0ortTnbCDlrX+FfzH4neLLsA=", "diagnosis"=>{"code"=>"tt02", "description"=>"description for tt02", "do_not_correctcase"=>"1"}, "commit"=>"Create Diagnosis"}
New diagnosis: {"code"=>"tt02", "created_at"=>nil, "description"=>"description for tt02", "updated_at"=>nil}
Diagnosis should be valid: true
code has value
I would dearly like to know what is the correct way to do all this, as I feel this is not very DRY or clean.
To teach myself Rails, im building an extremely simple Voting app.
There are 2 models, Question and Option. Question has_many Options and Option belongs_to Question.
Using the standard scaffolding, I have reached a stage where you can add a question, view it, and add options to it and see these options.
What I would like to do now is add the code that increases an option.count value by one when clicking on a link. I have a vote_up method in the Option model:
class Option < ActiveRecord::Base
validates :text, :presence => :true
belongs_to :question
def vote_up
self.count += 1
end
end
My Options controller looks like:
class OptionsController < ApplicationController
def create
#question = Question.find(params[:question_id])
#option = #question.options.create(params[:option])
redirect_to question_path(#question)
end
end
My Question model looks like:
class Question < ActiveRecord::Base
validates :text, :presence => {:message => 'A question normally has text...'}
has_many :options, :dependent => :destroy
def vote
# Maybe the vote code will go here???
end
end
And my Question controller has the usual new, create, edit, destroy methods that the scaffold creates. V little customisation here.
My show.html.erb view where I would like to put the link to the vote method looks like:
<p id="notice"><%= notice %></p>
<p>
<b>Question <%= #question.guid %></b>:
<%= #question.text %>
</p>
<% if #question.options.count == 0 %>
<p>Shame! there are currently no options to vote on. Add some! </p>
<% elsif #question.options.count == 1 %>
<p>One option in a vote is a dictatorship... Maybe add some more?</p>
<% end %>
<h2>Options:</h2>
<% #question.options.each do |option| %>
<p>
<%= option.text %>: ** Link to vote here!
</p>
<% end %>
<h2>Add an option to vote on</h2>
<%= form_for([#question, #question.options.build]) do |f| %>
<div class="field">
<%= f.label :text %><br />
<%= f.text_field :text %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<% if #question.options.count == 0 # Only show edit if no options saved. %>
<%= link_to 'Edit', edit_question_path(#question) %> |
<% end %>
<%= link_to 'Back', questions_path %>
So what I am trying to do is add a "vote" link next to each option that calls the vote_up method in the options model. This is probably laughably easy, but i've hit a wall and would really appreciate any help.
Also, any suggestions on how to do this better would be welcome!
Thanks
Simon
I think #oded-harth has showed a right way, but I have two remarks:
First of all, Rails is a beautiful language and is written to simplify our developer lives ;) When programming in Rails you must never forget that. With this in mind, I want to point you to "increment()" method. So you can simply up-vote without unnecessary += 1. To down-vote use decrement(). I believe you can use it like this: option.increment(:count)
Second, I think it's a little dirty to have a whole form for a simple vote action. You can use something like this
<%= link_to "Vote Up", :url => { :action => :vote_up, :option_id => option.id }, :method => :put %>
To make it work you'll have to set your route something like this:
resources :votes
put :vote_up
end
What I would do is make the vote_up method in the controller:
def vote_up
option = Option.find(params[:option_id])
option.count += 1
redirect (to where do you want...)
end
And in the view I would call that method this way:
<%= form_for( option, :url => { :action => "vote_up", :option_id => option.id} ) do |f| %>
<%= f.submit("vote up") %>
<% end %>