Extra line breaks with simple_format - ruby-on-rails

To practice Ruby on Rails, I am creating a blog which includes a text area (following Mackenzie Child's tutorial). Unfortunately, line breaks are included every time I press enter. How can I remove the extra line breaks?
show.html.erb
<h1><%= #post.title %></h1>
<p><%= simple_format(#post.body) %></p>
_form.html.erb
<div class="form">
<%= form_for #post do |f| %>
<%= f.label :title %><br>
<%= f.text_field :title %><br>
<br>
<%= f.label :body %><br>
<%= f.text_area :body %><br>
<br>
<%= f.submit %>
<% end %>
</div>
posts_controller.rb
class PostsController < ApplicationController before_action :authenticate_user!, except: [:index, :show]
def index
#posts = Post.all.order('created_at DESC')
end
def new
#post = Post.new
end
def create
#post = Post.new(post_params)
#post.save
redirect_to #post
end
def show
#post = Post.find(params[:id])
end
def edit
#post = Post.find(params[:id])
end
def update
#post = Post.find(params[:id])
if #post.update(params[:post].permit(:title, :body))
redirect_to #post
else
render 'edit'
end
end
def destroy
#post = Post.find(params[:id])
#post.destroy
redirect_to posts_path
end
private
def post_params
params.require(:post).permit(:title, :body)
end
end
So I type the following into the text area:
for j in 1..array.length-1
key = array[j]
i = j - 1
But this is what posts:
for j in 1..array.length-1
key = array[j]
i = j - 1
And if remove simple_format, it removes all new lines, which I don't want either.
In the developer tools:
<p>
" for j in 1..array.length-1
"
<br>
" key = array[j]
"
<br>
" i = j - 1
"
<br>

I’m going to assume, that because you are wrapping the body content in show.html.erb, that you don’t mind the data in your database but just want to clean it up to present it.
Have you tried:
<p><%= strip_tags #post.body %></p>
Rails API Reference

I could be misunderstanding the question, but I think you're getting confused about the purpose of simple_format.
simple_format takes some text that has line breaks in it and formats it as basic HTML by replacing 2 or more line breaks as paragraphs and single line breaks as <br> tags. This is what you would use to display a post to a visitor to the blog.
When you want the text of an existing blog post in a textarea then you want to leave the line breaks in the text intact, which is achieved using <%= f.text_area :body %> without wrapping in a call to simple_format.

Related

Rails 5.0 Error: ActiveModel::ForbiddenAttributesError [duplicate]

This question already has answers here:
ActiveModel::ForbiddenAttributesError when creating new user
(8 answers)
Closed 6 years ago.
I'm attempting to make a blog post on my web-app updatable from the browser, but when I click update in the edit for, I get this error:
ActiveModel::ForbiddenAttributesError
error in pots_controller line 33:
if #post.update_attributes(params[:post])
this is my edit.html.erb code:
<h1>Edit Post</h1>
<%= form_for #post do |f| %>
<p>
<%= f.label :title %><br />
<%= f.text_field :title %><br />
</p>
<p>
<%= f.label :body %><br />
<%= f.text_field :body %><br />
</p>
<p>
<%= f.select :category_id, Category.all.collect {|x| [x.name, x.id]}, {:include_blank => "Select One"} %><br />
</p>
<p>
<%= f.submit "Update post" %>
</p>
<% end %>
<%= link_to "Go Back", post_path %>
this is my posts_controller.rb code:
class PostsController < ApplicationController
def index
#posts = Post.find(4,5)
end
def show
#post = Post.find(params[:id])
end
def new
#post = Post.new
#category = Category.all
end
def create
#post = Post.new(params[:post])
if #post.save
redirect_to posts_path, :notice => "Your post has been saved"
else
render "new"
end
end
def edit
#post = Post.find(params[:id])
end
def update
#post = Post.find(params[:id])
if #post.update_attributes(params[:post])
redirect_to post_path, :notice => "Your post has been updated"
else
render "edit"
end
end
def destroy
#post = Post.find(params[:id])
#post.destroy
redirect_to posts_path, :notice => "Your post has been deleted"
end
end
hope and thank anyone can help. Best, M
Strong Parameters
Rails uses a security mechanism called Strong Parameters by default. Its purpose is to ensure that only certain fields can be updated via a user submitted form.
#post.update_attributes(params[:post]) is an old-style syntax which does not work with strong parameters.
The updated convention is as follows
class PostsController
def update
# ...
#post.update(post_params) # instead of passing params[:post] directly, you pass it a strong parameters whitelist (see below)
end
def post_params
# we construct a strong parameters whitelist below
# require(:post) means that the `params` hash MUST contain a :post key
# permit(:title, :body, ...) = here we enumerate the attributes which we will accept from the form parameters; it acts as a whitelist
params.require(:post).permit(:title, :body, ...)
end
end
If you use rails g scaffold you can see an example of a controller which uses strong parameters.
DON'T DO THIS: To disable using strong parameters by default, you can set the following config value
config.active_record.whitelist_attributes = false
I included this for completeness' sake, however you should not do this as it will unnecessarily introduce security vulnerabilities to your code.
Additional Resources
ActiveModel::ForbiddenAttributesError when creating new user
http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html
https://github.com/rails/strong_parameters

Doing Subtracting on my Rails App with user input

I'm just starting to learn Rails so please forgive the dumb question. In my web app, I was able to set up working models, forms, and view. A user is able to input their decimal answer and it shows on the web page perfectly. However, I want to subtract one user input from another user input. So if the user inputs 100 in one model "post.price" and 10 in another input model "ratings1.content" > I want it to show 90 in the "fprice.content3". Any help that you guys can give me would be so amazing, I feel like the issue might be in my controller for fprice. I have listed below all my relevant code. Thank you again :)
_form.html "post.price"
<%= simple_form_for #post do |f| %>
<%= f.input :title %>
<%= f.input :image %>
<%= f.input :price %>
<%= f.button :submit %>
<% end %>
_form.html "ratings1s.content"
<%= simple_form_for ([#post, #post.ratings1s.build]) do |f| %>
<%= f.input_field :content %>
<% end %>
_form.html "fprice.content3"
<%= simple_form_for ([#post, #post.fprices.build]) do |f| %>
<%= f.input_field :content3 %>
<% end %>
Rails Controller "fprices"
class FpricesController < ApplicationController
before_action :authenticate_user!
def create
#post = Post.find(params[:post_id])
#fprice = Fprice.create(params[:fprice].permit(:content3))
#fprice.content3 === #post.price - #ratings1.content
#fprice.user_id = current_user.id
#fprice.post_id = #post.id
if #fprice.save
redirect_to post_path(#post)
else
render 'new'
end
end
end
Rails Controller "ratings1s"
class Ratings1sController < ApplicationController
before_action :authenticate_user!
def create
#post = Post.find(params[:post_id])
#ratings1 = Ratings1.create(params[:ratings1].permit(:content))
#ratings1.content *= 10
#ratings1.user_id = current_user.id
#ratings1.post_id = #post.id
if #ratings1.save
redirect_to post_path(#post)
else
render 'new'
end
end
end
It appears that at no point in time are you every defining #ratings1 object, then you call the content method on it while the value of #ratings1 is nil and thats what cause the error. Maybe something like this should help:
class FpricesController < ApplicationController
before_action :authenticate_user!
def create
#post = Post.find(params[:post_id])
#fprice = Fprice.create(params[:fprice].permit(:content3))
#ratings1 = #post.ratings1s.last
#fprice.content3 = #post.price - #ratings1.content
#fprice.user_id = current_user.id
#fprice.post_id = #post.id
if #fprice.save
redirect_to post_path(#post)
else
render 'new'
end
end
end
I think this line is also a the problem
#fprice.content3 === #post.price - #ratings1.content
=== is an equality operator so I don't know why you would have it there replace it with this
#fprice.content3 = #post.price - #ratings1.content

Preserve newline in text area with Ruby on Rails

To practice Ruby on Rails, I am creating a blog which includes a text area (following Mackenzie Child's tutorial). When the text is submitted, all of the newlines are removed. I know variations of the question have been asked already, but I have been unable to replicate any of the results despite an entire day trying. I am not very familiar with JQuery.
Is there a set of steps that will preserve the newlines?
_form.html.erb
<div class="form">
<%= form_for #post do |f| %>
<%= f.label :title %><br>
<%= f.text_field :title %><br>
<br>
<%= f.label :body %><br>
<%= f.text_area :body %><br>
<br>
<%= f.submit %>
<% end %>
</div>
posts_controller.rb
class PostsController < ApplicationController before_action :authenticate_user!, except: [:index, :show]
def index
#posts = Post.all.order('created_at DESC')
end
def new
#post = Post.new
end
def create
#post = Post.new(post_params)
#post.save
redirect_to #post
end
def show
#post = Post.find(params[:id])
end
def edit
#post = Post.find(params[:id])
end
def update
#post = Post.find(params[:id])
if #post.update(params[:post].permit(:title, :body))
redirect_to #post
else
render 'edit'
end
end
def destroy
#post = Post.find(params[:id])
#post.destroy
redirect_to posts_path
end
private
def post_params
params.require(:post).permit(:title, :body)
end
end
Newlines are actually being preserved(as \r\n), you just don't see them in your index/show views.
In these views, call simple_format on your post.body field to replace \ns with <br>s(HTML newlines):
simple_format(post.body)
From docs:
simple_format(text, html_options = {}, options = {}) public
Returns text transformed into HTML using simple formatting rules.
Two or more consecutive newlines(\n\n) are considered as a paragraph and wrapped
in <p> tags. One newline (\n) is considered as a linebreak and a <br /> tag is
appended. This method does not remove the newlines from the text.
An easier (and dare I say better) way to handle this is to apply this CSS style to the paragraph or similar HTML element that you use to display user input inside of.
white-space: pre-wrap;
One advantage is this will persevere newlines just like simple_format without adding the extra formatting that it applies, such as turning two consecutive newlines characters into a paragraph element or automatically adding newlines to the end of the content. Just switched from using simple_format to this myself in a similar project. Way more predictable.
I agree with Gino's answer, except I find that using:
white-space: pre-line
instead helps me to eliminate unnecessary whitespace at the beginning of the first line of my emails.
Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/white-space

NoMethodError on section 5.7 of Rails Guide

I'm following the Getting Started tutorial for Rails 4.0.0 located here:
http://guides.rubyonrails.org/getting_started.html
I'm at the point in section 5.7 where I'm supposed to be getting the ActiveModel::ForbiddenAttributes error. Instead, I get this error:
NoMethodError in Posts#show
Showing C:/Rails/blog/app/views/posts/show.html.erb where line #8 raised:
undefined method `text' for nil:NilClass
Extracted source (around line #8):
5
6 <p>
7 <strong>Text:</strong>
8 <%= #post.text %>
9 </p>
Despite this, I believe the posts are being created, since the ids are being incremented each time I submit the form. I am brand new to Rails, and have attempted to exactly follow the instructions.
I'm running Windows 7 x64, with Ruby 1.9.3 and Rails 4.0.0.
Here are some relevant files; please let me know if any other are required.
posts_controller.rb:
class PostsController < ApplicationController
def new
end
def create
#post = Post.new(post_params)
#post.save
redirect_to #post
end
private
def post_params
params.require(:post).permit(:title, :text)
end
def show
#post = Post.find(params[:id])
end
end
show.html.erb:
<p>
<strong>Title:</strong>
<%= #post.title %>
</p>
<p>
<strong>Text:</strong>
<%= #post.text %>
</p>
new.html.erb
<h1>New Post</h1>
<%= form_for :post, url: posts_path do |f| %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
Just write down show method after create method, as your show method is below the keyword private it is taking private as a Access Modifier and hence can't access directly through browser
class PostsController < ApplicationController
def new
end
def create
#post = Post.new(post_params)
#post.save
redirect_to #post
end
def show
#post = Post.find(params[:id])
end
private
def post_params
params.require(:post).permit(:title, :text)
end
end
I was having the same problem with the tutorial (which at this date (11/18/14) uses 'articles' instead of 'posts'), and found the solution to be the placement of the following "def" block in articles_controller.rb:
def show
#article = Article.find(params[:id])
end
Here's what it looks like for me:
class ArticlesController < ApplicationController
def new
end
def create
#article = Article.new(article_params)
#article.save
redirect_to #article
end
def show
#article = Article.find(params[:id])
end
private
def article_params
params.require(:article).permit(:title, :text)
end
end

can some one tell me what the correct syntax of the ruby posts GET is?

I am trying to write a rails app and it keeps bombing on this one line of code in my controller.rb file:
posts GET /posts(.:format) posts#show
Can some one help me?
I am running ruby 1.9.3p429 (2013-05-15 revision 40747) [x86_64-darwin12.4.0]
with rails 3.2.13
UPDATE
I took out the line of code above and now I can't get rails to post the value (tag) of the selected check box. Can I get some guidance?
Here is my posts_controller.rb file:
class PostsController < ApplicationController
def new
end
def create
#post = Post.new(params[:post].permit(:check_box, :label))
#post.save
redirect_to #post
end
def show
#post = Post.find(params[:id])
end
def index
#posts = Post.all
end
private
def post_params
params.require(:post).permit(:check_box, :label)
end
end
Here is my new.html.erb file:
<h1>SWORD Mock Device Page</h1>
<%= form_for :post, url: posts_path do |f| %>
<p>
<h2>Android Phones</h2>
<%= f.check_box(:razr_max1) %>
<%= f.label(:razr_max1, "Droid Razr Max #1") %>
</p>
<p>
<%= f.check_box(:galaxyS2) %>
<%= f.label(:galaxyS2, "Samsung Galaxy S2") %>
</p>
<p>
<h2>Android Tablets</h2>
<%= f.check_box(:asusprime3) %>
<%= f.label(:asusprime3, "Asus Transormer Prime #3") %>
</p>
<p>
<%= f.check_box(:motoxoom1) %>
<%= f.label(:motoxoom1, "Motorola Xoom #1") %>
</p>
<p>
<%=f.submit "Select" %>
</p>
<% end %>
here is my routes.rb:
SWORDMockDev::Application.routes.draw do
resources :posts
root to: "landing#index"
end
and my show.html.erb:
<p>
<strong>Device:</strong>
<%= #post.title %>
</p>
Any help is greatly appreciated!!
Thanks!!
ironmantis7x
Instead of:
def create
#post = Post.new(params[:post].permit(:check_box, :label))
#post.save
redirect_to #post
end
You can do:
def create
#post = Post.new(post_params)
#post.save
redirect_to #post
end
The label is not going to submit in the post, only the value of the checkbox
I recommend you to use pry https://github.com/pry/pry and in the controller in the create you can do:
def create
binding.pry
#post = Post.new(post_params)
#post.save
redirect_to #post
end
And you can see what comes in the params, and what's going on. Also checkout your routes and see if everything is ok with:
rake routes

Resources