I'm working on a dynamic form in a Rails app, and I need to insert a variable number of records into a model in a single form submission. I've done this using PHP -> MySQL/Postgres before, but I have no idea how to do it in Rails.
Ultimately, users should be able to create any number of records to be inserted, but in my example below, I'm limiting it to 2... let me see if I can do that, first...
Here's the form - the ids all get a unique suffix because they are being populated dynamically from localStorage objects on submission.
new.html.erb
<%= form_for #entry, html: {id: :new_entry_form} do |f| %>
<% for i in 0..1 %>
<%= f.text_field :name, :id => 'name_#{i}' %>
<%= f.text_field :day, :id => 'day_#{i}' %>
<% end %>
<% end %>
Here's the associated controller - I'm sure that this is missing something, but I don't know what.
def new
#entry = Entry.new
end
def create
#entry = Entry.create(entry_params)
redirect_to "http://localhost:3000/entries"
end
private
def entry_params
params.require(:entry).permit(:name, :day)
end
Any help would be much appreciated.
Follow this link it shows how to create multiple object in one form submit:
http://vicfriedman.github.io/blog/2015/07/18/create-multiple-objects-from-single-form-in-rails/
Related
I've a settings controller setup like this:
class Admin::SettingsController < ApplicationController
def index
#settings = Setting.all
end
def update
setting_params.each do |key, value|
Setting.where(key: key).first.update_attribute :value, value
end
redirect_to admin_settings_path, notice: "Settings saved."
end
private
def setting_params
params.require(:settings).permit(:site_title, :site_desc)
end
end
The index action has a view file in relevant path, its code is as follows:
<h1>Settings</h1>
<%= form_tag admin_settings_path, method: "put" do %>
<p>
<label>Site Title:</label>
<%= text_field_tag "settings[site_title]" %>
</p>
<p>
<label>Site Description:</label>
<%= text_field_tag "settings[site_desc]" %>
</p>
<p>
<%= submit_tag "Save settings" %>
</p>
<% end %>
Now, I'm able to save/update these fields data in relevant model and I can see the data through command Setting.all in rails console. But the issue is, after saving the record via form when I reload the settings index page the form is blank and it is not showing previously saved values in the fields.
What I'm doing wrong here?
You can do what has been mentioned in the previous answer i.e. using a form_for. However, this can also be accomplished by creating a Hash in both the controller actions that creates and processes this form.
In the action that creates this form, the values in the hash could be initialized to blanks/zeros depending upon the input tag and in the action that processes this form, the values in the hash could be assigned to the values obtained from the posted params[].
I ran into the similar issue with form_tag and I used the following code in my index action i.e. the action that renders the form initially:
#search = {name: "", ranking_group: 0}
Whereas, in the search action, I used the following code to fill up this hash:
#search = {name: params[:name], ranking_group: params[:ranking_group]}
Finally, in the view, I used the appropriate default value options with the input tags as below:
<%= text_field_tag :name, #search[:name] %>
<%= select_tag :ranking_group, options_for_select(AmenityEntities::Amenity.ranking_group_options, #search[:ranking_group]), include_blank: true %>
Hope this helps.
I think you need to use form_for(#variable) instead of just a form_tag because you need to persiste the object after save.
form_for works with resources, take a look here: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html
I am making one of my first rails apps from scratch and cannot figure out what is going on. Whenever I try to create a new instance, it saves multiple instances of the item. I am trying to make tasks, and each time I create a new instance it saves 7 times, and then gives me an error page saying no data received. I tried adding a uniqueness validator for the model, but that would save the first instance then return me to root path. This is what I have:
Task Controller:
class TasksController < ApplicationController
def index
#tasks = Task.all
end
def create
#task = Task.new(task_params)
if #task.save
redirect_to 'tasks'
else
redirect_to root_path
end
end
private
def task_params
params.require(:task).permit(:title, :category, :difficulty)
end
end
Here is the form I am using, perhaps that is the problem?
<div id='task_form'>
<%= form_for :task do |f| %>
<%= f.label :title %>
<%= f.text_field :title%>
<%= f.label :category %>
<%= f.text_field :category%>
<%= f.label :difficulty %>
<%= f.text_field :difficulty%>
<%= f.submit %>
<% end %>
</div>
Thanks if anyone knows what this is or has experienced it before
Do this:
#app/controllers/tasks_controller.rb
def new
#task = Task.new
end
#app/views/tasks/new.html.erb
<%= form_for #task do |f| %>
--
Problem
I frankly don't know why you're getting multiple submits, but I can see one of the issues you have is you're using a symbol in place of an instance variable.
This wouldn't normally be an issue, but as you're experiencing these problems, I would certainly use an instance variable in the form. (if only to test).
This does several important things:
Using an #instance var creates an ActiveRecord object for your form
The use of an ActiveRecord object gives rails a definite structure for the object
By saving the object, Rails is able to populate the appropriate attributes etc
I would certainly try the above code, but there may be other issues at work here if your form is submitting 7 times.
I have a controller that looks like this:
def new
#columns = Column.where(:table_id => #table.id)
#row = Row.new(id: #table.id)
end
def create
row_params.each do |row_param|
#row = Row.new(row_param)
#row.column_id = params["column_id"]
if #row.save
redirect_to collection_rows_path, notice: 'item was successfully created.'
else
render action: 'new'
end
end
end
I have a form that looks like:
<%= form_for [#table, #row] do |f| %>
<% #columns.each do |column| %>
<%= column.id %>
<%= hidden_field_tag :column_id, column.id %>
<%= f.label :data %><br>
<%= f.text_field :data %>
<% end %>
<%= f.submit %>
<% end %>
Basically, I'm trying to send multiple params and have them inserted with the column. But I keep getting this error:
undefined methodstringify_keys' for ["data", "No"]:Array` when there is two columns which means there is two text fields and I insert "Hello" in the first one, and "No" in the second.
Two things: Why is it only reading the "No" on the second one instead of both the "Hello" and "No"? And also why am I getting this error?
Thanks for all help!
Answers to your questions:
It is only reading "No" which is your input in the last "Data" text_field since the two text_fields generated in your form_for save their input value in the same params key which is params[:row][:data]. What happens then is the latest value saved to the params[:row][:data] key overrides any previous value it had.
The error undefined method stringify_keys' for ["data", "No"]:Array happens because you create 2 text_fields with the same name which is :data. When you submit the form, an Array is being submitted instead of a String that Rails expects when using text_field.
Solution to your problem:
This seems like an ideal use case for using a nested model form. Basing on your code, it looks like Row belongs_to Table. So in your Table model you'll need to add this code:
#app/models/table.rb
accepts_nested_attributes_for :row
Then add the following code in your RowsController:
#app/controllers/rows_controller.rb
def new
#columns = Column.where(:table_id => #table.id)
#columns.each do |column|
#table.rows.build(column_id: column.id)
end
end
def create
#table = Table.new(table_params)
if #table.save
redirect_to collection_rows_path, notice: 'item was successfully created.'
else
render :new
end
end
private
def table_params
params.require(:table).permit(rows_attributes: [:data, :column_id])
end
Then in your 'rows#new' view:
#app/views/rows/new.html.erb
<%= form_for #table, url: rows_path ,method: :post do |f| %>
<%= f.fields_for :rows do |r| %>
<%= r.object.column.name %>
<%= r.hidden_field :column_id, value: r.object.column_id %>
<%= r.label :data %><br>
<%= r.text_field :data %>
<% end %>
<%= f.submit %>
<% end %>
What the above code will do is allow you to create multiple rows for a column according to the number of columns the table has. This won't work though if a #table has no #columns yet. This assumes that you've created #columns for the #table already. Basing on your code though, it seems like that's already what you're doing.
you want to store 'data' as array in Row
In Rails model Row add
serialize :data, Array
in view
text_field_tag 'row[data][]'
You are getting only 'No' because form for does not know its an array so , it picks the last one And you are getting this error because rails does not know you want to store it as array , it excepts a string but got an array instead.
In a rails project I have two entities, Users and Institutions, they have a many-to-many relationship.
The views for them are set up to create new users and institutions but I want to have another view for linking the two.
In rails console all I have to do is
myuser.institutions << the_institution_i_just_created
The controller can do some of the work but how do I handle the submissions and the forms? I want to use a selection box so that the input is limited to the Institutions already in existence.
<select id="institution_selection" name="institution_sel">
<% selections = []
Institution.all.each do |institution|
pair = [institution.name, institution.id]
selections.concat([pair])
end
%>
<%= options_for_select(selections) %>
</select>
So the question in summary is how do I map this submission to an object so that in the controller I can do add it to the relation?
The solution was:
Alright, so this is the solution I came up with, I'm sure there is a better way to go about it and I'll continue to look into it but at least I got something close to what I was aiming for
def test
if !session[:user]
redirect_to users_path, notice: "Please login first"
end
if params[:institution]
#user = User.find(session[:user])
#institution = Institution.find(params[:institution][:id])
#user.institutions << #institution
redirect_to #user, notice: "Institution was successfully added "
end
end
and for the view
<%= form_tag("/users/test", :method => "post") do %>
<%= collection_select :institution, :id, Institution.all, :id, :name %>
<%= submit_tag("Search") %>
<% end %>
Use collection_select
<% from for #instancevar do |form| %>
<%= form.collection_select :institution_id, Institution.all, :id, :name %>
# Do other stuff....
<% end %>
Ok guys, so I'm making a scheduler.
So I have two tables so far,
Shows with "title:string" and "description:text" and I also have
ShowTime; with "show_id:integer", "day:string", and "show_time:time".
I did the has_many, and belongs_to, I honestly do not know where to go from here on,
I want a user to be able to add the times when creating a new show. What would I do? I was looking at some rails associations documentations, seems like I would be making something like,
#showtime = #shows.showtimes.create(:show_id => show.id, :day => DAY, :show_time => TIME)
Notice I put just DAY and TIME, because I also honestly don't know how I'll fetch this data.
It really depends on your interface. But for simplicity, let's assume you provided two select boxes for selecting day and time, and have to add ShowTime one by one.
And assume you have rest resources:
map.resources :shows do |show|
show.resources :show_times
end
The form: (given a #show object created already)
<% form_for #show_time, :url => show_show_time_path(#show) do |form| %>
<%= form.label :day %>: <%= form.select :day, [["Mon", "mon"], ["Tue", "tue"]], {} %>
<%= form.label :show_time %>: <%= form.select :show_time, [["Slot 1", "09:00"]], {} %>
<% end %>
You should provide your best way to generate the day & show_time arrays. They are in the following structure:
[["Text", "value"], ["Text", "value"]]
which will generate something like:
<option value="value">Text</option>
After the form is submitted, in your create action:
def create
#show = Show.find params[:show_id] # this params[:show_id] is from the rest resource's path
#show_time = #show.show_times.build(params[:show_time]) # this params[:show_time] is from the form you submitted
if #show_time.save
flash[:notice] = "Success"
redirect_to show_show_time_path(#show, #show_time)
else
flash[:notice] = "Failed"
render :action => "new"
end
end