Quick one. I'm trying to push a parameter into the database when i'm creating an object. I have it working if I force the integer as with the commented code below however for whatever reason I cannot get it to be added to the database is I use the params[:subscription_id] method. I can see the parameters in my server but cannot see it getting inserted into the certificates table. If i force the integer in my controller it will go through and I can see the subscriptions_id getting passed in.
Does this have any reason to do with my relationship being a has_one relationship perhaps?
Certificate Controller
class CertificatesController < ApplicationController
def new
#certificate = Certificate.new
end
def create
#certificate = Certificate.new(certificate_params)
#certificate.subscription_id = params[:subscription_id]
##certificate.subscription_id = 1
if #certificate.save
flash[:success] = "The certificate has been uploaded"
redirect_to :back
else
render 'new'
end
end
private
def certificate_params
params.require(:certificate).permit(:document, :title, :subscription_id)
end
end
View code:
<%= link_to "upload certificate", new_certificate_path(subscription_id: subscription.id) %>
Models
class Subscription < ActiveRecord::Base
belongs_to :user
belongs_to :course
has_one :certificate
end
class Certificate < ActiveRecord::Base
belongs_to :subscription
has_attached_file :document
#validates_attachment :document, content_type: %w(application/pdf application/msword application/vnd.openxmlformats-officedocument.wordprocessingml.document)
do_not_validate_attachment_file_type :document
end
Certificate Form
<div class="row">
<div class="site-forms">
<div class="col-md-10">
<%= simple_form_for #certificate do |f| %>
<!-- <= f.input :course_img, as: :file, required: true, label: "Please upload a brand image for your course" %><br> -->
<span class="btn btn-default btn-file">
<i class="fa fa-cloud-upload fa-lg"></i> Upload Image
<%= f.input :document, as: :file, required: true, label: false %>
</span> Please upload Certificate as PDF <br><br>
<%= f.input :title, placeholder: "Course Title", required: true, label: "Course Title" %>
<%= f.button :submit, class: "btn btn-primary" %>
<% end %>
</div>
</div>
</div>
This is probably something stupid i'm missing but I can get it to work if I force the integer in the commented out code in the controller. I'm nearly sure the params code is correct. Thanks.
Added logs
Started POST "/certificates" for ::1 at 2017-05-23 20:40:30 +0100
Processing by CertificatesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"6fV0xLOoy6ppNG7PYp37vkKqJnxU17nLPSK/mvbgH8k3s2LyaMEOJlekq5S0Ed4fpbNcqVe+cBsu5F38ACCmcg==", "certificate"=>{"document"=>#<ActionDispatch::Http::UploadedFile:0x007f954362c160 #tempfile=#<Tempfile:/var/folders/gx/86yj74bx3md88cfn2fwc975h0000gn/T/RackMultipart20170523-5261-1n2mwfl.png>, #original_filename="duck.png", #content_type="image/png", #headers="Content-Disposition: form-data; name=\"certificate[document]\"; filename=\"duck.png\"\r\nContent-Type: image/png\r\n">, "title"=>"Test"}, "commit"=>"Create Certificate"}
Command :: PATH=/usr/local/bin/:$PATH; file -b --mime '/var/folders/gx/86yj74bx3md88cfn2fwc975h0000gn/T/36846677e3a8f4c0b16d8bdf8ef1860820170523-5261-e90bny.png'
(0.1ms) begin transaction
Command :: PATH=/usr/local/bin/:$PATH; file -b --mime '/var/folders/gx/86yj74bx3md88cfn2fwc975h0000gn/T/36846677e3a8f4c0b16d8bdf8ef1860820170523-5261-1d907er.png'
SQL (0.3ms) INSERT INTO "certificates" ("document_file_name", "document_content_type", "document_file_size", "document_updated_at", "title", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?) [["document_file_name", "duck.png"], ["document_content_type", "image/png"], ["document_file_size", 49114], ["document_updated_at", "2017-05-23 19:40:30.662715"], ["title", "Test"], ["created_at", "2017-05-23 19:40:30.683041"], ["updated_at", "2017-05-23 19:40:30.683041"]]
(0.7ms) commit transaction
Redirected to http://localhost:3000/certificates/new?subscription_id=3
Completed 302 Found in 36ms (ActiveRecord: 1.1ms)
Started GET "/certificates/new?subscription_id=3" for ::1 at 2017-05-23 20:40:30 +0100
Processing by CertificatesController#new as HTML
Parameters: {"subscription_id"=>"3"}
Rendered certificates/_form.html.erb (7.7ms)
Rendered certificates/new.html.erb within layouts/application (8.7ms)
Rendered shared/_message.html.erb (0.1ms)
Completed 200 OK in 95ms (Views: 94.3ms | ActiveRecord: 0.0ms)
You need to set your subscription_id in a hidden field so that it gets passed in the params hash.
<%= f.hidden_field :subscription_id, :value => params[:subscription_id] %>
That way it gets set with the rest of the params.
Params are strings. Try
#certificate.subscription_id = params[:subscription_id].to_i
Try change this function as below
def certificate_params
params.require(:certificate).permit(:document, :title, :subscription_id, :subscription)
end
Maybe allow permit subscription field from params.
Related
Rails 4: While running a feature spec with Capybara, my params hash is nil.
What am I doing wrong here?
# app/views/comics/index.html.erb
<%= form_tag subscriptions_subscribe_path do %>
<%= label_tag :email %>
<%= text_field_tag :email, params[:email]%>
<%= submit_tag 'Submit'%>
<% end %>
# spec/features/subscribe_feature_spec.rb
require 'rails_helper'
require 'pry'
feature 'subscribe to email list' do
scenario 'success' do
visitor_email = 'Monkey#Biz.com'
visit '/'
fill_in :email, with: visitor_email
click_on 'Submit'
# ...balance omitted...
end
end
# app/controllers/subscriptions_controller.rb
class SubscriptionsController < ApplicationController
def subscribe
binding.pry
# params = nil ... WHY?
# params[:email] => undefined method `email' for nil:NilClass
# ...balance omitted...
end
end
I've got a bonehead error somewhere in the code above.
My view contains only a single instance of the word "Submit", so Capybara is not clicking the wrong link.
logs
$ tail -f log/test.log
Started GET "/" for 127.0.0.1 at 2016-03-19 15:01:07 -0700
Processing by ComicsController#index as HTML
Comic Load (0.3ms) SELECT "comics".* FROM "comics"
Rendered comics/index.html.erb within layouts/application (12.4ms)
Rendered shared/_navlinks.html.erb (1.4ms)
Rendered shared/_navlinks.html.erb (0.1ms)
Completed 200 OK in 349ms (Views: 348.6ms | ActiveRecord: 0.3ms)
Started POST "/subscriptions/subscribe" for 127.0.0.1 at 2016-03-19 15:01:08 -0700
Processing by SubscriptionsController#subscribe as HTML
Parameters: {"utf8"=>"✓", "email"=>"Monkey#Biz.com", "commit"=>"Submit"}
I'm trying to implement follow/unfollow features to my application among users. I am using devise + omniauth and using a separate users controller. When I click on follow button, it does not do anything with the numbers that is supposed to count the following / followers,etc. in the console i get these errors
Processing by RelationshipsController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"ReTtZn0GbB7f5LROr6FLnw40ErDDcubDa8/yLnyVd/FIhxM3qjZI8pjYDAGmuGJiv1paGVjhp/LMVmFtkcZVwQ==", "followed_id"=>"1", "commit"=>"Follow"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 2]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
(0.1ms) begin transaction
WARNING: Can't mass-assign protected attributes for Relationship: followed_id
app/models/user.rb:21:in `follow'
app/controllers/relationships_controller.rb:7:in `create'
(0.1ms) commit transaction
Relationship Load (0.3ms) SELECT "relationships".* FROM "relationships" WHERE "relationships"."follower_id" = ? AND "relationships"."followed_id" = ? LIMIT 1 [["follower_id", 2], ["followed_id", 1]]
Rendered users/_unfollow.html.erb (11.5ms)
Rendered relationships/create.js.erb (13.9ms)
Completed 500 Internal Server Error in 38ms
ArgumentError (First argument in form cannot contain nil or be empty):
app/views/users/_unfollow.html.erb:1:in `_app_views_users__unfollow_html_erb___2456782614560778317_70319555077280'
app/views/relationships/create.js.erb:1:in `_app_views_relationships_create_js_erb__3841758023410302021_45366420'
app/controllers/relationships_controller.rb:8:in `create'
My lines of code are as follows
relationship_controller
class RelationshipsController < ApplicationController
before_filter :authenticate_user!
def create
#user = User.find(params[:followed_id])
current_user.follow(#user)
respond_to do |format|
format.html { redirect_to #user }
format.js
end
end
def destroy
#user = Relationship.find(params[:id]).followed
current_user.unfollow(#user)
respond_to do |format|
format.html { redirect_to #user }
format.js
end
end
end
_follow_form.html.erb
<div id="follow_form">
<% if current_user.following?(#user) %>
<%= render 'unfollow' %>
<% else %>
<%= render 'follow' %>
<% end %>
</div>
_unfollow.html.erb
<%= form_for(current_user.active_relationships.find_by(followed_id: #user.id),
html: { method: :delete },
remote: true) do |f| %>
<%= f.submit "Unfollow", class: "btn" %>
<% end %>
create / destroy .js.html
$("#follow_form").html('<%= escape_javascript(render('users/unfollow')) %>')
$("#followers").html('<%= #user.followers.count %>')
$("#follow_form").html('<%= escape_javascript(render('users/follow')) %>')
$("#followers").html('<%= #user.followers.count %>')
Thank you in advance.. I am dying to figure this out...
EDITED My error trackbacks
Your error is that the form submitted was empty/nil.
This is due to not accepting the form and its attributes.
Add this to your controller
private
def private_params
params[:yourmodel].permit(:yourkeys, :anotherkey]
end
I was able to fix this problem through removing protected_attributes gem in my old gem. It is a remnant of the rails 3 and clashes with the new rails 4. So, if anyone is having issues. Please remove this gem and be aware that rails 4 is using strong parameters now.
Thanks.
I had almost the same error as you, I can't recall exactly.
For me, everything was working great, the follow/unfollow feature was working but when I unfollowed a user I was always getting this kind of error.
The solution for me was to change the unfollow form_for to a link_to :
<%= link_to current_user.active_relationships.find_by(followed_id: #user.id), remote: true, method: :delete, data: { confirm: 'Are you sure?' } do %>
<button class="btn" type="submit">Unfollow</button>
<% end %>
And the error disappeared.
Take a look at this simple & quick tutorial for more infos.
I've built a simple app that has businesses, and those businesses have many reviews. I'm using a partial _form to create/update reviews. The create action works fine, but the update action creates a new review instead of updating the review like its supposed to. Here's the relevant code (irrelevant code removed for brevity):
Code from routes.rb:
resources :businesses do
resources :reviews
end
Code from models/business.rb:
class Business < ActiveRecord::Base
has_many :reviews, dependent: :destroy
validates_associated :reviews
end
Code from models/review.rb:
class Review < ActiveRecord::Base
belongs_to :business
belongs_to :user
end
Code from controllers/reviews_controller.rb:
class ReviewsController < ApplicationController
load_and_authorize_resource
before_filter :load_business
def new
end
def index
end
def create
#review = #business.reviews.create(review_params)
#review.user_id = current_user.id
#review.reviewer = current_user.first_name + ' ' + current_user.last_name
if #review.save
redirect_to business_path(#business)
flash[:notice] = 'Review posted!'
else
redirect_to business_path(#business)
flash[:danger] = 'Your review has an error. Please double check!'
end
end
def edit
#review = #business.reviews.find(params[:id])
end
def update
#review = #business.reviews.find(params[:id])
if #review.update(params[review_params])
redirect_to businesses_path(#business)
flash[:notice] = 'Review updated!'
else
render :action => 'edit'
end
end
def destroy
#review = #business.reviews.find(params[:id])
#review.destroy
redirect_to business_path(#business)
flash[:notice] = "Review deleted."
end
private
def load_business
#business = Business.find(params[:business_id])
end
def review_params
params.require(:review).permit(:review, :rating)
end
end
Code for `reviews/_form.html.erb:
<%= simple_form_for([#business, #business.reviews.build]) do |f| %>
<%= f.error_notification %>
<p>
<%= f.input :review %>
</p>
<p>
<%= f.input :rating, collection: 1..10 %>
</p>
<p>
<%= f.submit :class => 'btn btn-primary' %>
</p>
<% end %>
The reviews are rendered in the business#show view as a partial. Code for `reviews/_review.html.erb:
<% if !review.user_id.nil? %>
<div class="well">
<p>
<strong>Reviewer:</strong>
<%= review.reviewer %>
</p>
<p>
<strong>Review:</strong>
<%= review.review %>
</p>
<p>
<strong>Rating:</strong>
<%= review.rating %>
</p>
<span class = "timestamp">
posted <%= time_ago_in_words(review.created_at) %> ago.
</span>
<% if can? :update, review %>
<span class = "timestamp">
<%= link_to "Edit", [:edit, review.business, review], class: 'btn btn-small' %>|
<%= link_to "Delete", [review.business, review], method: :delete,
data: { confirm: 'Are you sure?' } %>
</span>
<% end %>
</div>
<% end %>
Code for reviews/edit.html.erb:
<h1>Edit Review</h1>
<%= render 'form', review: #review %>
<button type="button" class="btn btn-default"><%= link_to 'Back', businesses_path %></button>
The weird thing is, when I click on the "Edit" link in _review.html.erb, the URL that's generated appears to be correct, for example I get http://localhost:3000/businesses/10/reviews/82/edit. However, the _form.html.erb is empty where I would expect it to be populated with the current data for review #82. Furthermore, when I click the "Create Review" button, it creates a new review and doesn't edit review #82.
Here's the server logs after I click "Edit" for an existing review:
Started GET "/businesses/3/reviews/81/edit" for 127.0.0.1 at 2014-08-28 19:18:58 -0500
Processing by ReviewsController#edit as HTML
Parameters: {"business_id"=>"3", "id"=>"81"}
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = 8 ORDER BY "users"."id" ASC LIMIT 1
Review Load (6.9ms) SELECT "reviews".* FROM "reviews" WHERE "reviews"."id" = $1 LIMIT 1 [["id", 81]]
Business Load (0.5ms) SELECT "businesses".* FROM "businesses" WHERE "businesses"."id" = $1 LIMIT 1 [["id", 3]]
Review Load (27.4ms) SELECT "reviews".* FROM "reviews" WHERE "reviews"."business_id" = $1 AND "reviews"."id" = $2 LIMIT 1 [["business_id", 3], ["id", 81]]
Rendered reviews/_form.html.erb (107.0ms)
Rendered reviews/edit.html.erb within layouts/application (143.4ms)
Completed 200 OK in 967ms (Views: 669.2ms | ActiveRecord: 35.6ms)
Started POST "/businesses/3/reviews" for 127.0.0.1 at 2014-08-28 19:19:23 -0500
Processing by ReviewsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"<redacted>", "review"=>{"review"=>"Edit review #81.", "rating"=>"1"}, "commit"=>"Create Review", "business_id"=>"3"}
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = 8 ORDER BY "users"."id" ASC LIMIT 1
Business Load (0.6ms) SELECT "businesses".* FROM "businesses" WHERE "businesses"."id" = $1 LIMIT 1 [["id", 3]]
(28.9ms) BEGIN
SQL (132.9ms) INSERT INTO "reviews" ("business_id", "created_at", "rating", "review", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["business_id", 3], ["created_at", "2014-08-29 00:19:23.470750"], ["rating", 1], ["review", "Edit review #81."], ["updated_at", "2014-08-29 00:19:23.470750"]]
(39.7ms) COMMIT
(0.3ms) BEGIN
SQL (0.9ms) UPDATE "reviews" SET "reviewer" = $1, "updated_at" = $2, "user_id" = $3 WHERE "reviews"."id" = 83 [["reviewer", "<redacted>"], ["updated_at", "2014-08-29 00:19:23.692880"], ["user_id", 8]]
(17.5ms) COMMIT
Redirected to http://localhost:3000/businesses/3
Completed 302 Found in 553ms (ActiveRecord: 221.6ms)
Started GET "/businesses/3" for 127.0.0.1 at 2014-08-28 19:19:23 -0500
Processing by BusinessesController#show as HTML
Parameters: {"id"=>"3"}
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = 8 ORDER BY "users"."id" ASC LIMIT 1
Business Load (0.5ms) SELECT "businesses".* FROM "businesses" WHERE "businesses"."id" = $1 LIMIT 1 [["id", 3]]
(0.5ms) SELECT AVG("reviews"."rating") AS avg_id FROM "reviews" WHERE "reviews"."business_id" = $1 [["business_id", 3]]
Rendered reviews/_form.html.erb (5.7ms)
Review Load (0.6ms) SELECT "reviews".* FROM "reviews" WHERE "reviews"."business_id" = $1 ORDER BY "reviews"."id" DESC [["business_id", 3]]
Rendered reviews/_review.html.erb (58.1ms)
Rendered businesses/show.html.erb within layouts/application (173.5ms)
Rendered users/_avatar.html.haml (13.1ms)
Rendered layouts/_navigation.html.haml (30.9ms)
Rendered layouts/_messages.html.haml (1.5ms)
Rendered layouts/_footer.html.haml (16.5ms)
Rendered layouts/_analytics.html.haml (0.6ms)
Rendered layouts/_javascripts.html.haml (0.5ms)
Completed 200 OK in 421ms (Views: 391.5ms | ActiveRecord: 2.3ms)
It's clear that the second action in the server log is "Started POST..." which isn't correct. While I'm at it, I may as well provide the relevant routes from rake routes:
business_reviews GET /businesses/:business_id/reviews(.:format) reviews#index
POST /businesses/:business_id/reviews(.:format) reviews#create
new_business_review GET /businesses/:business_id/reviews/new(.:format) reviews#new
edit_business_review GET /businesses/:business_id/reviews/:id/edit(.:format) reviews#edit
business_review GET /businesses/:business_id/reviews/:id(.:format) reviews#show
PATCH /businesses/:business_id/reviews/:id(.:format) reviews#update
PUT /businesses/:business_id/reviews/:id(.:format) reviews#update
DELETE /businesses/:business_id/reviews/:id(.:format) reviews#destroy
I've already tried implementing every answer I could find on here, but to no avail. The closest one I've found to being almost my exact problem was this one, but it didn't help either: Rails: Use same partial for creating and editing nested items
Many thanks.
According to your output in console, you've got a sql insert stmt before update stmt. Your code in the form cause it. #business.reviews.build will create new review object even when edit.
Update your form_for to:
<%= simple_form_for([#business, #review]) do |f| %>
Instead of #business.reviews.build. You should create objects in controller instead of view.
So you may need to new review objects in your new action too.
def new
#review = #business.reviews.build
end
I have some more suggestions for you to simplify your code that could make things easier.
Use review id to find review, instead of through business.
Such as code in edit and update, you could:
def edit
#review = Reviews.find(params[:id])
end
def update
#review = Reviews.find(params[:id])
...
end
Please i have an problem: my form is that
<%=form_for :abbonamentos, url: url_for( :controller => :abbonamentos, :action => :edit) do |f| %>
<div class="field">
<%= f.label :id%><br />
<%= f.text_field :id%>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
and my controller is that:
def edit
id = params[:abbonamentos][:id]
#b = Abbonamento.find_by_id(id)
#user = current_user
a=Abbonamento.find_by(user_id: #user.id)
if a and #b
a.update_column(:stato_ingresso, (a.stato_ingresso-1))
#stato = a.stato_ingresso
flash[:success] = "Abbonamento used"
redirect_to :scegli_posti
else
flash.now[:error] = "Non ha abbonamento lo deve acquistare."
end
end
I want to verify if the params id exist in the model Abbonamento...When i try i have error like this:
NoMethodError in AbbonamentosController#edit
undefined method `[]' for nil:NilClass
Thank you
Please may be I can not explain myself well. In the research I want to do I suppose the user is already registered in the Abbonamento table with his id (user_id). When the user registers in the table abbonamento, its registration that will be returned is abbonamento_id which can be 1 or 2 . When he wants to use the subscription, you will have to insert the code (abbonamento_id) there so that the application can check if the code is right or wrong before making an action. If this is true the application will make an action otherwise it will be another.
It is in fact that I would realize with rails. thank you
Started POST "/usa_abbonamento" for 127.0.0.1 at 2014-04-30 14:29:00 +0200
Processing by AbbonamentosController#edit as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"8Ydr6NPDkynPQd9zo42vgxNIsNSwz4SPkI0JNzfc4lQ=", "abbonamentos"=>{"id"=>"1"}, "commit"=>"Save Abbonamentos"}
[1m[35mUser Load (0.4ms)[0m SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'c2bc8173fcb2c5cce4b2606962859049830be6aa' LIMIT 1
[1m[36mAbbonamento Load (0.4ms)[0m [1mSELECT "abbonamentos".* FROM "abbonamentos" WHERE "abbonamentos"."user_id" = 1[0m
[1m[35mAbbonamento Load (0.3ms)[0m SELECT "abbonamentos".* FROM "abbonamentos" WHERE "abbonamentos"."id" IS NULL
Rendered abbonamentos/edit.html.erb within layouts/application (3.2ms)
Rendered layouts/_header.html.erb (1.1ms)
Rendered layouts/_footer.html.erb (0.1ms)
Completed 200 OK in 47ms (Views: 40.2ms | ActiveRecord: 1.2ms)
Change your controller code as,
def edit
id = params[:abbonamentos][:id]
#b = Abbonamento.where(:id => id)
#user = current_user
a=Abbonamento.where(:user_id => #user.id)
if a.present? and #b.present?
a.update_column(:stato_ingresso, (a.stato_ingresso-1))
#stato = a.stato_ingresso
flash[:success] = "Abbonamento used"
redirect_to :scegli_posti
else
flash.now[:error] = "Non ha abbonamento lo deve acquistare."
end
end
You can make use of present? or blank? method to check if row exists.
I've been trying like crazy to work through this permit error using some of the other StackOverflow postings, but can't seem to get past it. I've got a projects model & controller & a versions model & controller. Projects/##/versions/new is a form page to create a new version of project id ##. But when I click the submit button to create the version...it throws the following error in the VersionsController:
undefined method `permit' for "Submit Now! ":String
Extracted source (around line #36):
34
35
36
37
38
def version_params
params.require(:version).permit(:title)
end
end
Any and all help would be greatly appreciated...I've been trying to fix this for too long now. My Code is as follows:
ROUTES.RB
resources :users
resources :sessions, only: [:new, :create, :destroy]
resources :projects, only: [:create, :new, :show, :edit, :update, :destroy]
resources :projects do
resources :versions
end
# get "static_pages/home"
# get "static_pages/help"
# get "static_pages/about"
#The original routes above map to...
root 'static_pages#home'
match '/signup', to: 'users#new', via: 'get'
match '/signin', to: 'sessions#new', via: 'get'
match '/signout', to: 'sessions#destroy', via: 'delete'
match '/help', to: 'static_pages#help', via: 'get'
match '/about', to: 'static_pages#about', via: 'get'
match '/contact', to: 'static_pages#contact', via: 'get'
PROJECTS MODEL:
class Project < ActiveRecord::Base
has_many :users
has_many :versions, dependent: :destroy
validates :title, presence: true, length: { maximum: 100 }
validates :background, presence: true
validates :user_id, presence: true
default_scope -> { order('created_at DESC') }
end
VERSIONS MODEL:
class Version < ActiveRecord::Base
belongs_to :project
validates :title, presence: true, length: { maximum: 140 }
default_scope -> { order('created_at DESC') }
end
VERSIONS CONTROLLER:
class VersionsController < ApplicationController
def new
#version = Version.new
end
def show
#project = Project.find(params[:project_id])
#version = Version.find(params[:id])
end
def index
#versions = Version.paginate(page: params[:page])
end
def create
#project = Project.find(params[:project_id])
#version = #project.versions.create(version_params)
if #version.save
flash[:success] = "You've successfully added a version to this branch..."
redirect_to project_path(#project)
else
render 'new'
end
end
def edit
end
def update
end
def destroy
end
private
def version_params
params.require(:version).permit(:title)
end
end
NEW.HTML.ERB (new version form):
<% provide(:title, 'New Version') %>
<h1>Add a version to this project</h1>
<div class="row-fluid">
<div class="col-md-5 no-pad offset3">
<%= bootstrap_form_for #version, :url => project_versions_path do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.text_field :title %>
<br clear="all">
<%= f.submit "Submit Now! ", class: "btn btn-lg btn-primary" %>
<% end %>
</div>
</div>
PARAMS:
{"utf8"=>"✓",
"authenticity_token"=>"######AAAA",
"submit"=>"Submit Now! ",
"project_id"=>"51"}
Processing by VersionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"################=", "version"=>"Submit Now! ", "project_id"=>"51"}
Project Load (0.3ms) SELECT "projects".* FROM "projects" WHERE "projects"."id" = ? ORDER BY created_at DESC LIMIT 1 [["id", "51"]]
Completed 500 Internal Server Error in 3ms
NoMethodError (undefined method `permit' for "Submit Now! ":String):
app/controllers/versions_controller.rb:41:in `version_params'
app/controllers/versions_controller.rb:17:in `create'
I can recognize the problem in the params. You have this:
{"utf8"=>"✓",
"authenticity_token"=>"######AAAA",
"submit"=>"Submit Now! ",
"project_id"=>"51"}
You should have this:
{"utf8"=>"✓",
"authenticity_token"=>"######AAAA",
"project_id"=>"51",
"version"=>{"title"=>"Foo Bar"},
"button"=>""}
The reason this is a problem is because you do not have a version title being passed in the params, and you are trying to create a new version with the params. It instead looks for the closest thing which in this case happens to be the string "Submit Now!", but since "submit" is not permitted than strong params tosses it out.
It looks like you are creating your form correctly, it may be an issue with bootstrap_form_for. Can you post what the input output for title looks like in html on your form?
In the meantime I have two suggestions,
First thing that may solve the problem, is to change f.submit to f.button.
f.button will still create a submit button, but it allows you to name is in the way that you are trying to.
Also in the controller, you don't need to save after you call create. create will actually store it in the database, so you are saving it twice. You should either call new instead of create
#version = #project.versions.new(version_params)
if #version.save
of check if new record
#version = #project.versions.create(version_params)
unless #version.new_record?