I created a simple application that has a Product and an Image model. Product has_many Images and Images has an attached file attribute (paperclip).
I created a simple_form for creating/editing Products and it works fine on creation. However, when editing a Product that has N images, rails inserts more N files - empty files.
I have set up a Simple Form custom input that tests if the image attachment exists in which case instead of rendering the builders input, it only renders an image_tag().
I see the html generated and it show something strange, a hidden tag:
<input id="product_images_attributes_0_id" name="product[images_attributes][0][id]" type="hidden" value="14">
And in the rails server console I see:
Processing by ProductsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"asdfasdfaasdf=", "product"=>{"reference"=>"Y1112CYL.E2", "images_attributes"=>{"0"=>{"id"=>"14"}}}, "commit"=>"Update Product", "id"=>"20"}
Product Load (0.6ms) SELECT "products".* FROM "products" WHERE "products"."id" = $1 LIMIT 1 [["id", "20"]]
Unpermitted parameters: id
(0.2ms) BEGIN
SQL (1.0ms) INSERT INTO "images" ("created_at", "imageable_id", "imageable_type", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["created_at", Tue, 18 Feb 2014 05:05:13 UTC +00:00], ["imageable_id", 20], ["imageable_type", "Product"], ["updated_at", Tue, 18 Feb 2014 05:05:13 UTC +00:00]]
(0.6ms) COMMIT
Here is the code to my implementation. If someone could help I would be very happy! Please pardon me if I left out any import part of the code, I will gladly edit the question to include it.
_form.html.erb
<%= simple_form_for(#product) do |f| %>
<%= f.error_notification %>
<div class="inputs">
<%= f.input :reference %>
<h3>Images</h3>
<div id='images'>
<%= f.simple_fields_for :images do |image| %>
<%= render 'image_fields', :f => image %>
<% end %>
<div class='links'>
<%= link_to_add_association 'New image', f, :images %>
</div>
</div>
</div>
<div class="actions">
<%= f.button :submit %>
</div>
<%end%>
_image_fields.html.erb
<%= content_tag :div, class: "nested-fields images-fields" do %>
<%= content_tag :div, id: "new-image" do %>
<% if f.object.photo.exists? %>
<% f.template.image_tag(f.object.photo.url(:thumb)) %>
<% else %>
<% f.input :photo, :as => :photo %>
<% end %>
<% end %>
<% end %>
app/inputs/photo_input.erb
class PhotoInput < SimpleForm::Inputs::FileInput
def input
out = '' # the output string we're going to build
# check if there's an uploaded file (eg: edit mode or form not saved)
if object.send("#{attribute_name}?")
# append preview image to output
# <%= image_tag #user.avatar.url(:thumb), :class => 'thumbnail', id: 'avatar' %>
out << template.image_tag(object.send(attribute_name).url(:thumb), :class => 'thumbnail', id: 'photo')
else
# append file input. it will work accordingly with your simple_form wrappers
(out << #builder.file_field(attribute_name, input_html_options)).html_safe
end
end
end
ProductsController#update
def update
respond_to do |format|
if #product.update(product_params)
format.html { redirect_to #product, notice: 'Product was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
For posterity, #omarvelous' comment seems to have solved it:
I added the reject if all blank to my accepts_nested_attributes_for
accepts_nested_attributes_for :images, :allow_destroy => true, :reject_if => :all_blank
Edit:
It turns out there is an issue with this solution. When reject_if => :all_blank is it stops the destroy from working properly. See this post that shows a workaround -- that I did not manage to get to work.
Related
I have tried a few methods and checked all of the existing SO questions I can find and can't find an answer to the problem. I'm a Rails newbie.
I have these models:
Project (has_many WeeklyReflections, has_many ProjectTasks)
WeeklyReflection (belongs_to Project)
ProjectTask (belongs_to Project)
Standard devise user model
My Project show page displays a list of ProjectTasks for the week. Using simplecalendar.
I can navigate forward and back a week at a time, which then changes the URL from www.site.com/projects/3 to www.site.com/projects/3?start_date=2108-05-30, or www.site.com/projects/3?start_date=2108-05-13, and this then shows all the tasks related to that week.
What I want to do as well, is for each page create a weekly journal entry, only one of which can be created for the week, however, I'm having problems saving it to my controller - I've tried a few ways and also tried putting it in as a hidden field on a form, and still can't get it to work.
I've put start_date:<%= render inline: params[:start_date].inspect %> on both the Project show page and form it returns a value correctly, i.e. "start_date:"2018-04-28"" or it returns nil if on the default show page which is to be expected.
The two methods I've tried: are - accessing the start_date param via the controller (in the controller below) and also adding the following to the form:
<%= hidden_field_tag(:weekending, params[:start_date]) %> (I've also tried using .to_date, as I think the string it returns isn't in the right format)
However, both methods are returning a nil value when the start_date param is returning 2018-04-28 on the view page.
Console log after create action:
Started POST "/projects/6/weekly_reflections" for 2.96.199.78 at 2018-05-07 16:20:14 +0000
Cannot render console from 2.96.199.78! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by WeeklyReflectionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"UFCXjIp1SZrql2JckHk1HrzDlzO2/WLVwcdvdh+FQKbdrVMfdaivtjS32oLaFwcFs0UcupVP+XV6VVnNwrM0XQ==", "week_reflection"=>{"reflectionentry"=>"adasda", "motivationscore"=>"1", "beliefscore"=>"1"}, "weekending"=>"2018-04-28", "commit"=>"Create Project reflection", "project_id"=>"6"}
Project Load (0.6ms) SELECT "projects".* FROM "projects" WHERE "projects"."id" = ? LIMIT ? [["id", 6], ["LIMIT", 1]]
(0.1ms) begin transaction
(0.1ms) commit transaction
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 2], ["LIMIT", 1]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 2], ["LIMIT", 1]]
(0.1ms) begin transaction
SQL (1.3ms) INSERT INTO "week_reflections" ("reflectionentry", "user_id", "project_id", "motivationscore", "beliefscore", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?) [["reflectionentry", "adasda"], ["user_id", 2], ["project_id", 6], ["motivationscore", 1], ["beliefscore", 1], ["created_at", "2018-05-07 16:20:14.957131"], ["updated_at", "2018-05-07 16:20:14.957131"]]
(15.0ms) commit transaction
-
class WeeklyReflectionsController < ApplicationController
before_action :set_weekly_reflection, only: [:show, :edit, :update, :destroy]
before_action :set_project, only: [:new, :edit, :create, :show]
def index
#weekly_reflections= WeeklyReflection.all
end
def new
#weekly_reflection= WeeklyReflection.new
end
def create
#weekly_reflection= #project.weekly_reflections.create(project_reflection_params)
#weekly_reflection.user = current_user
#weekly_reflection.weekending = params[:start_date].to_date || Date.today.beginning_of_week
respond_to do |format|
if #weekly_reflections.save
format.html { redirect_to #weekly_reflection.project, notice: 'Weekly reflection was successfully created.' }
else
format.html { redirect_to #weekly_reflection.project, notice: 'Weekly reflection could not be added.' }
end
end
end
private
def weekly_reflection
#weekly_reflection= WeeklyReflection.find(params[:id])
end
def set_project
#project = Project.find(params[:project_id])
end
def weekly_reflection_params
params.require(:weekly_reflection).permit(:reflectionentry, :weekending, :motivationscore, :beliefscore)
end
end
Project show page:
<p id="notice"><%= notice %></p>
start_date:<%= render inline: params[:start_date].inspect %>
<div class="row well">
<div class="col-md-12">
<%= render 'project_detail' %>
</div>
<div class="col-md-12">
<% if #project.user == current_user && #project.active? %>
<br>
<%= render "project_tasks/task_modal" %>
<% end %>
</div>
<div class="col-md-12">
<%= render "project_reflection_calendar" %>
<% if #project.user == current_user && #project.active? %>
<h3>Add your thoughts for this week</h3>
<%= render "project_reflections/form_reflection" %>
<% end %>
</div
WeeklyEntry form, shown on the project show page:
<div class="row">
start_date:<%= render inline: params[:start_date].inspect %>
<%= form_for([#project, #project.weekly_reflections.build]) do |form| %>
<div class="col-md-12 projectform">
<%= form.label "Add your thoughts for this week" %>
<%= form.text_field :reflectionentry, :rows =>2, style: 'width:100%;' %>
</div>
<div class="col-md-7 projectform">
<%= form.label "How motivated are you for your project this week?" %>
<%= form.select :motivationscore, [1,2,3,4,5,6,7,8,9,10], class:"form-control" %>
</div>
<div class="col-md-7 projectform">
<%= form.label "How strongly do you believe you will reach your project?" %>
<%= form.select :beliefscore, [1,2,3,4,5,6,7,8,9,10], class:"form-control" %>
</div>
<%= hidden_field_tag(:weekending, params[:start_date].to_date) %>
<div class="col-md-12 projectform">
<%= form.submit class:"btn btn-primary" %>
</div>
<% end %>
</div>
ApplicationRecord code:
class WeeklyReflection < ApplicationRecord
belongs_to :project
belongs_to :user
validates :reflectionentry, presence:true, length: {minimum:3, maximum: 540}
#required for simple_calendar
def start_time
self.weekending
end
end
class Project < ApplicationRecord
has_many :project_tasks, dependent: :destroy
belongs_to :user
has_many :weekly_reflections, dependent: :destroy
end
=> WeeklyReflection Schema:
(id: integer, reflectionentry: text, user_id: integer, project_id: integer, weekending: date, motivationscore: integer, beliefscore: integer, created_at: datetime, updated_at: datetime)
I think, this should work:
Add to your ProjectController show action:
#weekly_reflection= #project.weekly_reflections.new
Change in WeeklyReflectionsController:
def create
#weekly_reflection = #project.weekly_reflections.new(weekly_reflection_params)
#weekly_reflection.user = current_user
respond_to do |format|
if #weekly_reflections.save
format.html { redirect_to #weekly_reflection.project, notice: 'Weekly reflection was successfully created.' }
else
format.html { redirect_to #weekly_reflection.project, notice: 'Weekly reflection could not be added.' }
end
end
end
private
def weekly_reflection_params
params.require(:weekly_reflection).permit(:reflectionentry, :weekending, :motivationscore, :beliefscore)
end
Change in WeeklyReflection form:
<div class="row">
<%= form_for #weekly_reflection do |form| %>
<div class="col-md-12 projectform">
<%= form.label "Add your thoughts for this week" %>
<%= form.text_field :reflectionentry, :rows =>2, style: 'width:100%;' %>
</div>
<div class="col-md-7 projectform">
<%= form.label "How motivated are you for your project this week?" %>
<%= form.select :motivationscore, [1,2,3,4,5,6,7,8,9,10], class:"form-control" %>
</div>
<div class="col-md-7 projectform">
<%= form.label "How strongly do you believe you will reach your project?" %>
<%= form.select :beliefscore, [1,2,3,4,5,6,7,8,9,10], class:"form-control" %>
</div>
<%= form.hidden_field :weekending, value: params[:start_date] || Date.today.beginning_of_week %>
<div class="col-md-12 projectform">
<%= form.submit class:"btn btn-primary" %>
</div>
<% end %>
</div>
Here we create #weekly_reflection variable inside the show action of ProjectsController, and just use it in form
That worked. Thanks so much.
With just a slight change to:
<%= form_for([#weekly_reflection.project, #weekly_reflection]) do |form| %>
I also had to add in:
<%= form.hidden_field :weekending, value: params[:start_date].try(:to_date).try(:beginning_of_week) || Date.today.beginning_of_week %>
So that I could capture the beginning of the week of the date in the param.
I create an application, which is basically a character creator for an RPG with interactive and dynamic forms. I use Rails 5.0.0.1, and I cannot update my form properly. The base model updates well, but all nested don't.
So, I have
class Character < ApplicationRecord
has_many :attr4characters, autosave: true
accepts_nested_attributes_for :attr4characters, allow_destroy: true
end
and
class Attr4character < ApplicationRecord
belongs_to :character
end
which represent a character and a set of his attributes. Each record in Attr4character is a different attribute.
The Show view is simple:
...
<div class="field">
<%= f.label :description %>
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.label :character_type %>
<%= f.select(:character_type, options_for_select(["Zhong Lung", "Shih", "Hsien", "Garou", "Technocrat"])) %>
</div>
<% f.object.attr4characters.each do |attr| %>
<%= f.fields_for attr do |attr_f| %>
<div class="field">
<%= attr_f.label "Field name" %>
<%= attr_f.text_field :field_name %>
</div>
<div class="field">
<%= attr_f.label "Field value" %>
<%= attr_f.text_field :field_value %>
</div>
<% end %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
...
And finally my characters_controller:
def update
respond_to do |format|
if #character.update(character_params)
format.html { redirect_to #character, notice: 'Character was successfully updated.' }
format.json { render :show, status: :ok, location: #character }
else
format.html { render :edit }
format.json { render json: #character.errors, status: :unprocessable_entity }
end
end
end
private
def set_character
#character = Character.find(params[:id])
end
def character_params
params.require(:character).permit(:id, :name, :player, :description, :character_type, attr4characters_attributes: [:id, :character_id, :field_name, :field_value])
end
So, I have a form, which correctly display a character and all set of his attributes. When I update a character field (like :description), it is normally updated. When I update any nested field, Rails says that character is successfully updated and nothing changes! I searched with Google, and I found a lot of problems with nested attributes in Rails forms, but none of the recipes worked for me. I even encountered opinions that it is a bug in Rails 4, but I use 5th version...
Please, advice on the topic. Is it a bug really? Or am I doing something wrong? I'm new on Rails, so I don't exclude that possibility. :)
By the way, in the server's log I found that there is warning about attr4characters.
Processing by CharactersController#update as HTML
Parameters: {"utf8"=>"\u2713", "authenticity_token"=>"xeYyIRc13YiOk29v18rFM6Oh5OHRRuPpSKEQuIHE/U4uhANEF7TwMp8mb6hv6L7mUAm5MngAuyFayHcWV/Vvbw==", "character"=>{"name"=>"Ray", "player"=>"111", "description"=>"A Zhong Lung suicider", "character_type"=>"Hsien", "attr4character"=>{"field_name"=>"Gift1", "field_value"=>"Sense Wyrm"}}, "commit"=>"Update Character", "id"=>"3"}
Character Load (0.2ms) SELECT "characters".* FROM "characters" WHERE "characters"."id" = ? LIMIT ? [["id", 3], ["LIMIT", 1]]
Unpermitted parameter: attr4character
(0.1ms) begin transaction
SQL (0.9ms) UPDATE "characters" SET "character_type" = ?, "updated_at" = ? WHERE "characters"."id" = ? [["character_type", "Hsien"], ["updated_at", 2016-09-13 14:39:10 UTC], ["id", 3]]
(24.3ms) commit transaction
But attr4characters are permitted in the characters_controller...
The warning is telling you that it is ignoring all the attr4character attributes. Your permit code is correct as is your model, but your view doesn't match them. You should be doing
f.fields_for :attr4characters do |attr_f|
...
end
And let rails handle iterating over the association. This will also ensure that attributes are named correctly (so they will be allowed through by your whitelist)
I'm on week two of this issue and have recently used the railsCast #196 (revised). I know this is older - maybe that's my issue. As an extra spin I'm hosting my rails server off Cloud 9.
I've tried following a few different tutorials just to get one going & this is as far as I've gotten. The weird part is none of their syntex matches what the official ruby on rails documentation has ... Rails View templates.
In the railsCast the guy is able to get blank fields to show up ... I'm not sure how...so I haven't managed to populate the question or answer fields yet. I'm not even sure what the two rails console messages mean - besides there aren't records there to be had.
Thanks for reading & any suggestions!
-M
Without further ado, my senario ... nested forms via templates as shown in railsCast 196 ...
My rails console ...
2.2.1 :045 > cc = Survey.first.questions.first
Survey Load (0.5ms) SELECT "surveys".* FROM "surveys" ORDER BY "surveys"."id" ASC LIMIT 1
Question Load (0.2ms) SELECT "questions".* FROM "questions" WHERE "questions"."survey_id" = ? ORDER BY "questions"."id" ASC LIMIT 1 [["survey_id", 1]]
=> nil
2.2.1 :046 > cc = Survey.first.questions
Survey Load (0.3ms) SELECT "surveys".* FROM "surveys" ORDER BY "surveys"."id" ASC LIMIT 1
Question Load (0.2ms) SELECT "questions".* FROM "questions" WHERE "questions"."survey_id" = ? [["survey_id", 1]]
=> #<ActiveRecord::Associations::CollectionProxy []>
My terminal console log ...
Started GET "/surveys/5/edit" for 68.54.21.200 at 2015-11-27 02:46:48 +0000
Cannot render console from 68.54.21.200! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by SurveysController#edit as HTML
Parameters: {"id"=>"5"}
Survey Load (0.4ms) SELECT "surveys".* FROM "surveys" WHERE "surveys"."id" = ? LIMIT 1 [["id", 5]]
Question Load (0.2ms) SELECT "questions".* FROM "questions" WHERE "questions"."survey_id" = ? [["survey_id", 5]]
Rendered surveys/_form.html.erb (4.2ms)
Rendered surveys/edit.html.erb within layouts/application (7.3ms)
Completed 200 OK in 70ms (Views: 67.9ms | ActiveRecord: 0.5ms)
So my code ...
surveys_controller.rb
class SurveysController < ApplicationController
def index
#surveys = Survey.all
end
def show
#survey = Survey.find(params[:id])
end
def new
#survey = Survey.new
3.times do
question = #survey.questions.build
4.times { question.answers.build }
end
end
def create
#survey = Survey.new(survey_params)
if #survey.save
flash[:notice] = "Successfully created survey."
redirect_to #survey
else
render :action => 'new'
end
end
def edit
#survey = Survey.find(params[:id])
end
def update
#survey = Survey.find(params[:id])
if #survey.update_attributes(params[:survey])
flash[:notice] = "Successfully updated survey."
redirect_to #survey
else
render :action => 'edit'
end
end
def destroy
#survey = Survey.find(params[:id])
#survey.destroy
flash[:notice] = "Successfully destroyed survey."
redirect_to surveys_url
end
private
def survey_params
params.required(:survey).permit(:id, :survey, :notice)
end
end
Edit action view
<% title = "Edit Survey" %>
<%= render 'form' %>
<p>
<%= link_to "Show", #survey %> |
<%= link_to "View All", surveys_path %>
</p>
_form.html.erb
<%= form_for(#survey) do |f| %>
<% if #survey.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#survey.errors.count, "error") %> prohibited this survey from being saved:</h2>
<ul>
<% #survey.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<% f.fields_for :questions do |builder| %>
<%= render "question_fields", :f => builder %>
<% end %>
<p><%= f.submit "Submit" %></p>
<% end %>
_question_fields.html.erb
<p>
<%= f.label :content, "Question" %><br />
<%= f.text_area :content, :rows => 3 %><br />
<%= f.check_box :_destroy %>
<%= f.label :_destroy, "Remove Question" %>
</p>
<% f.fields_for :answers do |builder| %>
<%= render 'answer_fields', :f => builder %>
<% end %>
_answer_fields.html.erb
<p>
<%= f.label :content, "Answer" %>
<%= f.text_field :content %>
<%= f.check_box :_destroy %>
<%= f.label :_destroy, "Remove" %>
</p>
In each of the 7 projects I ran off the web...
It was the nesting of the array's within the params.require() that was the problem.. It's one thing to tell someone it has to be nested - it's another to show them the syntax when they are new :)
Example:
// Note this is from memory, as I deleted this version of the github..so it's not exactly right or tested...
params.require(:survey).permit(:id,:questions => [:id, :survey_id, :question, :answers => [:id, :question_id, :answer]])
Here's the break down of that same example in depth:
params.require(:survey).permit(
:id,
:questions => [:id, // This is the 1st nesting
:survey_id, :question, :answers => [:id, // This is 1st nested array ":questions"
:question_id, :answer] // End the 2nd nested array ":answers"
] // End the 2nd array ":questions"
) // End the ":surveys" array & the .permit as a whole
I've tried to implement cocoon in my application, but having trouble saving data after the first input field.
I tried following the example, but no luck.
I'm able to save the first field into database, but nothing happens on the other fields when I add more.
_form.html.erb
<%= simple_form_for(#project) do |f| %>
<%= f.input :project_name %>
<%= f.hidden_field :user_id %>
<div id="tasks">
<%= f.simple_fields_for :tasks do |g| %>
<%= render 'task_fields', :f => g %>
<% end%>
<%= link_to_add_association 'add task', f, :tasks %>
</div>
<%= f.button :submit %>
<% end %>
_task_fields.html.erb
<li class="control-group nested-fields">
<div class="controls">
<%= f.label :task %>
<%= f.text_field :task %>
</div>
<%= link_to_remove_association "remove task", f %>
</li>
Controller
params.require(:project).permit(
:user_id, :project_name,
tasks_attributes: [:id, :task, :_destroy])
And I added:
//= require cocoon
in application.js
Project Model
class Project < ActiveRecord::Base
belongs_to :user
has_many :tasks
accepts_nested_attributes_for :tasks, :reject_if => :all_blank, allow_destroy: true
end
Task Model
class Task < ActiveRecord::Base
belongs_to :project
end
I think I got this correct? I'm able to click on "add task" link and a new field pops up, but those new fields doesn't save.
EDIT from POST in console
Processing by ProjectsController#create as HTML
Parameters: {
"utf8"=>"✓",
"authenticity_token"=>"blah",
"project"=>{"project_name"=>"cocoon test",
"tasks_attributes"=>{
"0"=>{"task"=>"fix this!",
"_destroy"=>"false"
}}},
"commit"=>"Create Project"}
(0.2ms) begin transaction
SQL (1.5ms) INSERT INTO "projects" ("project_name", "created_at", "updated_at") VALUES (?, ?, ?) [["project_name", "cocoon test"], ["created_at", "2015-07-15 03:26:09.444377"], ["updated_at", "2015-07-15 03:26:09.444377"]]
SQL (0.4ms) INSERT INTO "tasks" ("task", "project_id", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["task", "fix this!"], ["project_id", 8], ["created_at", "2015-07-15 03:26:09.450324"], ["updated_at", "2015-07-15 03:26:09.450324"]]
(8.4ms) commit transaction
Redirected to http://localhost:3000/projects/8
Completed 302 Found in 24ms (ActiveRecord: 10.4ms)
EDIT 2 posting project controller methods create and new
def create
#project = Project.new(project_params)
respond_to do |format|
if #project.save
format.html { redirect_to #project, notice: 'Project was successfully created.' }
format.json { render :show, status: :created, location: #project }
else
format.html { render :new }
format.json { render json: #project.errors, status: :unprocessable_entity }
end
end
end
def new
#project = Project.new
#project.tasks.build
end
i´m new to rails and like to know why my form does not write the data to the database?
if i show the data in the controller like
render text: params[:post].inspect
it is showing me the correct details. if i send the form to the database is showing just a new id and the created_at and updated_at data.
maybe there is someone who can help me...
here are my files:
LOG:
tarted POST "/manage/rooms" for 127.0.0.1 at 2014-03-12 09:45:28 +0100
Processing by Manage::RoomsController#create as HTML
Parameters: {"utf8"=>"✓","authenticity_token"=>"7IrPpFfkK4Krc4u6YYpUcaCp+",
"rooms"=>{"number_of_rooms"=>"1", "occupancy"=>"1", "room_type"=>"Private Room",
"gender"=>"mixed", "title"=>"foo"}, "commit"=>"Save Rooms"} (0.2ms) BEGIN
SQL (0.4ms) INSERT INTO "rooms" ("created_at", "updated_at") VALUES ($1, $2)
RETURNING "id" [["created_at", Wed, 12 Mar 2014 08:45:28 UTC +00:00],
["updated_at", Wed, 12 Mar 2014 08:45:28 UTC +00:00]] (660.8ms) COMMIT
Redirected to http://localhost:3000/manage/rooms/27
Completed 302 Found in 664ms (ActiveRecord: 661.3ms)
controller: ( controllers/manage/room_cont...)
class Manage::RoomsController < ApplicationController
def new
end
def create
#render text: params[:rooms].inspect
#room = Room.new(params[:room])
#room.save
redirect_to [:manage, #room]
end
def show
#room = Room.find(params[:id])
end
private
def room_params
params.require(:room).permit(:number_of_rooms, :occupancy, :room_type, :gender, :title)
end
end
model: (models/room.rb )
class Room < ActiveRecord::Base
end
form: ( /views/manage/rooms/form.html... )
<%= simple_form_for [:manage, #room], manage_room_path do |f| %>
<p>
<%= f.input :number_of_rooms, collection: 1..20, :include_blank => false %>
</p>
<p>
<%= f.input :occupancy, collection: 1..20, :include_blank => false %>
</p>
<p>
<%= f.input :room_type, collection: ["Private Room", "Shared Room (Dorm)"],:include_blank => false %>
</p>
<p>
<%= f.input :gender, collection: ["mixed", "male", "female"], :include_blank => false %>
</p>
<P>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
routes:
manage_rooms GET /manage/rooms(.:format) manage/rooms#index
POST /manage/rooms(.:format) manage/rooms#create
new_manage_room GET /manage/rooms/new(.:format) manage/rooms#new
edit_manage_room GET /manage/rooms/:id/edit(.:format) manage/rooms#edit
manage_room GET /manage/rooms/:id(.:format) manage/rooms#show
PATCH /manage/rooms/:id(.:format) manage/rooms#update
PUT /manage/rooms/:id(.:format) manage/rooms#update
DELETE /manage/rooms/:id(.:format) manage/rooms#destroy
Thanks!
In your create action:
#room = Room.new(room_params)
and in your room_params method, do: params.require(:rooms).permit...