Reputation: 99
I am new to Rails and I am trying to save a link to a database but when I submit the link only the time stamps are saved. If I try to use require
in my controller it says it is empty which confuses me even more.
Is this related to convention I am breaking which Rails does no like ?
index.html.erb
<%= form_for WatchedLink.new, url: {action: "create"}, html: {class: "links_to_be_scraped"} do |f| %>
<%= f.text_field (:link) %>
<%= f.submit "Save" %>
<% end %>
page_to_be_scraped_controller.rb
class LinksToBeScrapedController < ApplicationController
def index
@watched_links = WatchedLink.all
end
def show
@watched_links = WatchedLink.find(params[:id])
end
def new
@watched_links = WatchedLink.new
end
def create
@link = WatchedLink.new(params.permit(:watched_link))
if @link.save
puts "ADDED TO THE DATABASE #{params[:watched_link]}"
else
puts "FAILED TO ADD TO THE DATABASE"
end
end
def edit
end
def upadate
end
def delete
end
def destroy
end
end
Log
Started POST "/links_to_be_scraped" for 127.0.0.1 at 2018-02-11 03:19:04 +0000
Processing by LinksToBeScrapedController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"jMv4C+k0OSkgDAj/Rw6UcZX9hFZHhbG6P4Dcb/2oyeybnVRtuOqscQZEON0rjG0Q/s6Bp6zBlUQIsVEnL5ikiw==", "watched_link"=>{"link"=>"www.google.com"}, "commit"=>"Save"}
Unpermitted parameters: utf8, authenticity_token, watched_link, commit
(0.1ms) BEGIN
SQL (0.2ms) INSERT INTO `watched_links` (`created_at`, `updated_at`) VALUES ('2018-02-11 03:19:04', '2018-02-11 03:19:04')
(66.5ms) COMMIT
ADDED TO THE DATABASE {"link"=>"www.google.com"}
No template found for LinksToBeScrapedController#create, rendering head :no_content
Completed 204 No Content in 108ms (ActiveRecord: 66.7ms)
Started GET "/" for 127.0.0.1 at 2018-02-11 03:19:06 +0000
Processing by LinksToBeScrapedController#index as HTML
Rendering links_to_be_scraped/index.html.erb within layouts/application
WatchedLink Load (0.3ms) SELECT `watched_links`.* FROM `watched_links`
Rendered links_to_be_scraped/index.html.erb within layouts/application (9.0ms)
Completed 200 OK in 22ms (Views: 20.6ms | ActiveRecord: 0.3ms)
Upvotes: 1
Views: 230
Reputation: 33481
You're sending the form with the params { watched_link: { link: ... } }
, but in your controller your create
isn't accessing to watched_link.
Update name of the text_field tag helper in your form:
<%= form_for WatchedLink.new, url: { action: "create" }, html: { class: "links_to_be_scraped" } do |f| %>
<%= f.text_field :link %>
...
<% end %>
And in your controller:
@link = WatchedLink.new(params.require(:watched_link).permit(:link))
You could move the new argument used in create to a strong params definition, like:
private
def watched_link_params
params.require(:watched_link).permit(:link)
end
Then you can just update the create action to:
@links = WatchedLink.new(watched_link_params)
Also consider taking a look to the ActionController::StrongParameters
.
Upvotes: 1