ActiveModel::ForbiddenAttributesError in UrlsController#create - ruby-on-rails-4

I have the following code:
class UrlsController < ApplicationController
def new
#shortened_url = Url.new
end
def create
#shortened_url = Url.new(params[:url])
if #shortened_url.save
flash[:shortened_id] = #shortened_url.id
redirect_to new_url_url
else
render :action => "new"
end
end
def show
#shortened_url = Url.find(params[:id])
redirect_to #shortened_url.url
end
end
I'm getting the error I know is related to the required parameters and permit. Any one can tell me how the method need to be written?
this is the model:
class Url < ActiveRecord::Base
validates :url, :presence => true
end
the error is when submitting the form. I get
ActiveModel::ForbiddenAttributesError in UrlsController#create

It needed the use of strong parameters
class UrlsController < ApplicationController
def new
#shortened_url = Url.new
end
def create
#shortened_url = Url.new(shortened_url)
if #shortened_url.save
flash[:shortened_id] = #shortened_url.id
redirect_to new_url_url
else
render :action => "new"
end
end
def show
#shortened_url = Url.find(params[:id])
redirect_to #shortened_url.url
end
private
def shortened_url
params.require(:url).permit!
end
end

Related

How to restrict unsigned users from viewing certain static pages - Rails4

i am new to rails and your help would be much appreciated.
i want an unsigned user to be able to view only the static page landingpg but not the homepg & aboutpg
the static pages homepg & aboutpg can be viewed by unsigned users but for now i would like to restrict the unsigned users from viewing the homepg & aboutpg
could one advise me the best way to go about this?
class StaticPagesController < ApplicationController
respond_to :html, :xml, :json
def aboutpg
#timelines = Timeline.order("created_at DESC")
end
def homepg
#reviews = Review.limit(3).all
#search = Advert.search(params[:q])
#adverts = #search.result(distinct: true)
#companies = Company.all
end
def landingpg
#signup = Signup.new
end
end
route.rb
root 'static_pages#landingpg'
get 'about', to: 'static_pages#aboutpg'
get 'home', to: 'static_pages#homepg'
hi you need to add before_filter.
Class StaticPagesControlle < ApplicationController
before_filter :not_allowed ,:only => [:homepg,:aboutpg]
#rest is your code
end
#and in application controller or your StaticPageController do this
class ApplicationController < ActionController::Base
#define that method
def not_allowed
if current_user is unsigned (# here your logic for a user to be unsigend)
render json: {
status: 401,
message: 'You are not an authorised person to access this page'
}
end
end
Include a before_filter or before_action that will run a method before your action is called. If the method redirects to another path, then the call to the action is bypassed.
class StaticPagesController < ApplicationController
respond_to :html, :xml, :json
before_filter :user_allowed, only: [:aboutpg, :homepg]
def aboutpg
#timelines = Timeline.order("created_at DESC")
end
def homepg
#reviews = Review.limit(3).all
#search = Advert.search(params[:q])
#adverts = #search.result(distinct: true)
#companies = Company.all
end
def landingpg
#signup = Signup.new
end
def user_allowed
unless current_user
flash[:error] = "Please sign in first."
redirect_to root_path
end
end
end

How to make comment field in post in ruby on rails app

I want to add comment in post in simply ruby on rails application.
Resolved.
My Controller:
class CommentsController < ApplicationController
before_filter :authenticate_user!
def create
binding.pry
#adventure = Adventure.find(params[:adventure_id])
#comment = #adventure.comments.create(comment_params)
if #comment.save
flash[:notice] = "Comment has been created."
redirect_to #adventure
else
flash.now[:danger] = "error"
end
end
def comment_params
params.require(:comment).permit(:body)
end
end
class Comment < ActiveRecord::Base
belongs_to :adventure
end

How to Update a Rails 4 Form Input with methods and Regex

I'm currently making a URL shortener in Rails. The user can enter both the given_url and then also the slug they desire. I already have some http validation on given_url area using jquery validate, but I'd like to the preferred slug to be have no characters and whitespace.
I found the correct regex/whitespace and tested it in the console, so this works!
#slug_regex = slug.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '')
However, I'm not sure how to enter this into my overall Rails App. I attempted to do the validates on the links model, which slug is a column, but I don't want to just validate the correctness of it... I want to automatically update it.
I attempted to make a before_save private method in the links controller. Here is where i ended up this. It does not work. The error says :
NameError (uninitialized constant LinksController::Slug):
app/controllers/links_controller.rb:40:in `before_save'
class LinksController < ApplicationController
before_action :set_link, only: [:show]
before_action :before_save
def show
if params[:slug]
if redirect_to #link.given_url
#link.save
end
else
#link = Link.find(params[:id])
end
end
def new
#link = Link.new
end
def create
#link = Link.new(link_params)
respond_to do |format|
if #link.save
format.html { redirect_to root_path, notice: 'Link was successfully created.' }
format.js {}
format.json { render action: 'show', status: :created, location: #link }
else
format.html { render :new }
format.js {render file: 'links/errors.js.erb'}
end
end
end
private
def set_link
#link = Link.find_by(slug: params[:slug])
end
def before_save
slug = Slug.find_by(slug: params[:slug])
#slug_regex = slug.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '')
end
def link_params
params.require(:link).permit(:given_url, :slug)
end
end
Figured it out. Added a method to the model and called it before_save.
class Link < ActiveRecord::Base
before_save :format_slug
validates :given_url, presence: true
validates :slug, uniqueness: true
validates :slug, presence: true
def display_slug
ENV['BASE_URL'] + self.slug
end
private
def format_slug
self.slug = slug.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '')
end
end

Ruby - show related businesses

Each of my businesses belongs_to a category, so I'm trying to figure out how to show related businesses.
I'd like to limit it to three related businesses.
Thank you!
class BusinessesController < ApplicationController
respond_to :html, :xml, :json
before_filter :restrict_access, :only => [:edit, :update]
def index
#businesses = Business.all
respond_with(#businesses)
end
def show
#business = Business.friendly.find(params[:id])
if request.path != business_path(#business)
redirect_to #business, status: :moved_permanently
end
end
def new
#business = Business.new
3.times { #business.assets.build }
respond_with(#business)
end
def edit
#business = get_business(business_params)
#avatar = #business.assets.count
#avatar = 3-#avatar
#avatar.times {#business.assets.build}
end
def create
#business = Business.new(business_params)
if #business.save
redirect_to #business, notice: 'Business was successfully created.'
else
3.times { #business.assets.build }
render 'new'
end
end
Update the show action as below:
def show
#business = Business.friendly.find(params[:id])
#others = #business.category.businesses.where.not(id: #business.id).limit(3)
if request.path != business_path(#business)
redirect_to #business, status: :moved_permanently
end
end
#others will have <=3 businesses other than the current business belonging to the same category of current business. You can then use #others in the show view easily.

Querying Active Records and Foreign Key Help [Rails 4]

I know there are probably many different ways to do this, but using http://guides.rubyonrails.org/active_record_querying.html, I have been unable to find the best way that works for me.
I am making a forum using RoR, and I came across a problem when deleting posts from topics.
Each Topic has many posts. Each post has one topic.
When you post in the topic, it updates the topic table with who last posted and the time. However, when you delete a post, it keeps the old data of the post.
When I delete a post, I need to update the topic table with the previous post's data.
I know after deleting, I need to query all the posts in a topic, find the last one and use its data to update the topic.
How do I do that though?
The Query would be something like
SELECT * FROM posts WHERE (topic_id = topic.id) ORDER BY id DESC
Post Controller
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
def index
#posts = Post.all
end
def show
end
def new
#post = Post.new
end
def edit
#post = Post.find(params[:id])
end
def create
#post = Post.new(
:content => params[:post][:content],
:topic_id => params[:post][:topic_id],
:user_id => current_user.id)
if #post.save
#topic = Topic.find(#post.topic_id)
#topic.update_attributes(
:last_poster_id => current_user.id,
:last_post_at => Time.now)
flash[:notice] = "Successfully created post."
redirect_to "/topics/#{#post.topic_id}"
else
render :action => 'new'
end
end
def update
#post = Post.find(params[:id])
if #post.update_attributes(params[:post].permit!)
#topic = Topic.find(#post.topic_id)
#topic.update_attributes(:last_poster_id => current_user.id, :last_post_at => Time.now)
flash[:notice] = "Successfully updated post."
redirect_to #post
else
render :action => 'edit'
end
end
def destroy
#post = Post.find(params[:id])
#post.destroy
**# WHAT QUERY STATEMENT GOES HERE**
#topic.update_attributes(
:last_poster_id => #post.user_id,
:last_post_at => #post.created_at)
redirect_to "/topics/#{#post.topic_id}"
end
end
Try using this code:
def destroy
#post = Post.find(params[:id])
#topic = #post.topic
#post.destroy
last_post = #topic.reload.posts.last
#topic.update_attributes(last_poster_id: last_post.user_id, last_post_at: last_post.created_at)
redirect_to #topic
end