Undefined method to_slug in Page controller - ruby-on-rails-3

I cant understand my this is not working. I am trying to add a method to create a slug from the title of a page when the user creates a new page (using Ruby on Rails).
This is my create method:
def create
#page = Page.new(params[:page])
#page.user_id = current_user.id
#page.slug = #page.title.to_slug
respond_to do |format|
if #page.save
format.html { redirect_to #page, notice: 'Page was successfully created.' }
format.json { render json: #page, status: :created, location: #page }
else
format.html { render action: "new" }
format.json { render json: #page.errors, status: :unprocessable_entity }
end
end
end
Adn this is my method at the bottom of the same same controller. (pages_controller.rb) :
def to_slug(param=self.slug)
# strip the string
ret = param.strip
#blow away apostrophes
ret.gsub! /['`]/, ""
# # --> at, and & --> and
ret.gsub! /\s*#\s*/, " at "
ret.gsub! /\s*&\s*/, " and "
# replace all non alphanumeric, periods with dash
ret.gsub! /\s*[^A-Za-z0-9\.]\s*/, '-'
# replace underscore with dash
ret.gsub! /[-_]{2,}/, '-'
# convert double dashes to single
ret.gsub! /-+/, "-"
# strip off leading/trailing dash
ret.gsub! /\A[-\.]+|[-\.]+\z/, ""
ret
end
The slug method is from this question:
Best way to generate slugs (human-readable IDs) in Rails
I cant understand why this creates a method undefined error or how to fix it. Any help, hint or answer is appreciated. :)

The to_slug method is an instance method of PagesController class. The object #page.title don't have this method, that's the reason why the code not working.
There are several ways to make the method to_slug work, such as helper, decorate. But I think the best way is to put such logic into model, because slug is actually part of the model. We'll make slug attribute available instantly before saving(create and update).
So, in Page model. Assume you already have slug attribute.
Step 1: Setup callback
before_saving :update_slug # for create record, before actual saving
Step 2: update_slug method
def update_slug
ret = self.title # Use title variable directly
# .... You to_slug code. Almost same.
self.slug = ret # return slug
end
The above are basic ideas to provide a thought, not verified yet. Please check and verify it by yourself. Hope that helps.

Related

Needs redirects for routing

I'm very excited about Camaleon cms for rails 5; however, I've noticed a significant problem with posts that have parent slugs or have post-type slugs in the url as a url format.
For background, it's very important that a post's content can only be reached via one single url. Otherwise, you have the potential for getting penalized in google for having duplicate content. For those who rely on search engine traffic (basically everyone who would ever use a CMS), this is a very serious issue.
The following is an example of the issue. All of these urls will render the same post content:
http://www.example.com/parent_slug/post_slug
http://www.example.com/post_slug
http://www.example.com/parent_slug_blah_blah/post_slug
Or
http://www.example.com/post_type/post_slug
http://www.example.com/post_slug
http://www.example.com/post_type_blah_blah/post_slug
The way Wordpress deals with this issue is to redirect to the proper url with the correct parent slug if it doesn't exist or if it is misspelled.
My question here is for those in the know, is this perhaps a priority issue in one of the upcoming releases?
I'm not sure if this will work for everyone, but here's my solution to this issue.
Requirements: this will only work for posts that have the "post_of_posttype", "heirarchy_post" or "post_of_category_post_type" route formats.
The following code is extending the functionality of Camaleon's frontend controller method render_post by simply adding a redirect when the params don't match the #post.the_path. Seems to work for my purposes. Hopefully it will help someone else.
Create a new file in your config/initializers folder and place the following code:
# config/initializers/camaleon_custom_post.rb
CamaleonCms::FrontendController.class_eval do
# render a post
# post_or_slug_or_id: slug_post | id post | post object
# from_url: true/false => true (true, permit eval hooks "on_render_post")
def render_post(post_or_slug_or_id, from_url = false, status = nil)
if post_or_slug_or_id.is_a?(String) # slug
#post = current_site.the_posts.find_by_slug(post_or_slug_or_id)
elsif post_or_slug_or_id.is_a?(Integer) # id
#post = current_site.the_posts.where(id: post_or_slug_or_id).first
else # model
#post = post_or_slug_or_id
end
unless #post.present?
if params[:format] == 'html' || !params[:format].present?
page_not_found()
else
head 404
end
else
#post = #post.decorate
if ["post_of_posttype","hierarchy_post"].include? #post.the_post_type.contents_route_format
if params[:parent_title].nil? && params[:post_type_title].nil?
params_path = "/" + params[:slug]
elsif !params[:parent_title].nil?
params_path = "/" + params[:parent_title] + "/" + params[:slug]
elsif !params[:post_type_title].nil?
params_path = "/" + params[:post_type_title] + "/" + params[:slug]
end
unless (#post.the_path === params_path)
redirect_to #post.the_url, status: 301 and return
end
elsif #post.the_post_type.contents_route_format === "post_of_category_post_type"
if [params[:post_type_title],params[:label_cat],params[:category_id],params[:title]].all?
params_path = [params[:post_type_title],params[:label_cat],params[:category_id] + "-" + params[:title],params[:slug]].join("/")
params_path.prepend("/")
unless (#post.the_path === params_path)
redirect_to #post.the_url, status: 301 and return
end
else
redirect_to #post.the_url, status: 301 and return
end
end
#object = #post
#cama_visited_post = #post
#post_type = #post.the_post_type
#comments = #post.the_comments
#categories = #post.the_categories
#post.increment_visits!
# todo: can_visit? if not redirect home page
home_page = #_site_options[:home_page] rescue nil
if lookup_context.template_exists?("page_#{#post.id}")
r_file = "page_#{#post.id}"
elsif #post.get_template(#post_type).present? && lookup_context.template_exists?(#post.get_template(#post_type))
r_file = #post.get_template(#post_type)
elsif home_page.present? && #post.id.to_s == home_page
r_file = "index"
elsif lookup_context.template_exists?("post_types/#{#post_type.the_slug}/single")
r_file = "post_types/#{#post_type.the_slug}/single"
elsif lookup_context.template_exists?("#{#post_type.slug}")
r_file = "#{#post_type.slug}"
else
r_file = "single"
end
layout_ = nil
meta_layout = #post.get_layout(#post_type)
layout_ = meta_layout if meta_layout.present? && lookup_context.template_exists?("layouts/#{meta_layout}")
r = {post: #post, post_type: #post_type, layout: layout_, render: r_file}
hooks_run("on_render_post", r) if from_url
if status.present?
render r[:render], (!r[:layout].nil? ? {layout: r[:layout], status: status} : {status: status})
else
render r[:render], (!r[:layout].nil? ? {layout: r[:layout]} : {})
end
end
end
end
Seems kind of strange the mandatory redirect for non-accurate urls is not in the core camaleon application, but perhaps most people who use this cms are creating internally facing apps. Anyway, if that's not the case, I think this should be a priority fix.

Rails 3: accept all params except a specific value

I have a Rails 3.2.13 Application to maintenance.
Because of authorization rules i want to limit the find(params[:file_registry_id]) method to accept all parameters except 752. (Only user tehen should be able to get it.)
def show
if current_user.tehen?
#file_registry = FileRegistry.find(752)
else
#file_registry = FileRegistry.find(params[:file_registry_id])
end
#rubric = Rubric.find(params[:id])
#rubrics = expanded_rubrics #rubric.ancestors_with_self.collect(&:id)
set_favorites
render :action => 'index'
end
Is there a method available to filter an element (here id 752) from the params hash? Or what's the best way to go?
Simple solution:
def show
#file_registry = get_file_registry
#....
end
private
def get_file_registry
if current_user.tehen?
FileRegistry.find(752)
else
unless params[:file_registry_id] == FORBIDDEN_ID_FOR_GUEST
FileRegistry.find(params[:file_registry_id])
else
false
end
end
end
FORBIDDEN_ID_FOR_GUEST should be defined outside of the controller, for example inside of a initializer.
But I suggest to use a authorization library like CanCan (https://github.com/ryanb/cancan) where you can define permissions for every use case.

How to stop a helper method from applying to a specific controller?

I have a helper_method that allows links to escape from a subdomain. However it is impacting my videos_controller, as it essentially seems to negate the 'current_event' method when not in the events controlller.
I've tried several dozen different ways over the last 4 days to make it so I can still escape my links from the subdomain, but still allow the videos_controller to work.
I think the best way to achieve this is to exclude the videos_controller from the helper method, but I'm not sure how (or if it is actually the best way forward - I'm obviously a noob!) Any suggestions please?! Relevant code below:
module UrlHelper
def url_for(options = nil)
if request.subdomain.present? and request.subdomain.downcase != 'www' and !options.nil? and options.is_a?(Hash) and options.has_key? :only_path and options[:only_path]
options[:only_path] = false
end
super
end
end
Videos_controller
def new
if current_event?
#video = current_event.videos.new
else
#video = Video.new
end
end
def create
if current_event.present?
#video = current_event.videos.new(params[:video])
#video.user_id = current_user.id
key = get_key_from_the_cloud
#video.key = key
else
#video = current_user.videos.new(params[:video])
#video.user_id = current_user.id
key = get_key_from_the_cloud
#video.key = key
end
if #video.save
flash[:success] = "Video uploaded!"
redirect_to root_url(subdomain: => current_event.name)
else
flash[:error] = "#{#video.errors.messages}"
render :new
end
end
current_event method
def current_event
if request.subdomain.present?
#event = Event.find_by_name(request.subdomain)
end
end
Did you take a look at this post yet?
You might want to create a new function test that only does something like
module UrlHelper
def test
puts "Test is called"
end
end
If that works you know its not including that fails but it has to be the method.
Otherwise you know the module is not included and you can narrow down the search.

Local Jump Error No block given (yield) error on find_each

I'm trying to step through a list of records that are retrieved with find_each.
I patterned my controller code on the answer in this stack overflow post, but I'm still getting a "No Block Given (Yield)" error.
I'm just getting started in Ruby and Rails and I haven't yet found a full fledged explanation (lots of basic examples though) of blocks and yield that gives me what I need.
My code looks like this:
def select_save
#class = params[:class]
#student_id = params[:id]
#class.each do |id|
old_subject = Subject.find(id)
new_subject = old_subject.dup
new_subject.student_id = #student_id
new_subject.save
Assignment.find_each.where(:subject_id => id) do |assignments|
assignments.each do |a|
new_assignment = a.dup
new_assignment.subject_id = new_subject.id
new_assignment.save
end
end
end
respond_to do |format|
format.html { redirect_to #student, :notice => 'Subject and assignments created.' }
end
end
and the error points to the line with find_each.
I know I need a block to yield to, but how exactly that would look in this particular case escapes me.
Thanks for any suggestions.
You're passing a block to where and no block to find_each. You can't do that. You need to reverse find_each and where on this line, the order is important as the block is passed to the last method invoked:
Assignment.find_each.where(:subject_id => id) do |assignments|
It should read:
Assignment.where(:subject_id => id).find_each do |assignments|
Your next problem is you're trying to iterate over assignments, which is a single Assignment. find_each is already doing the iteration for you, passing one assignment into the block at a time. The block should read:
Assignment.where(:subject_id => id).find_each do |assignment|
new_assignment = assignment.dup
new_assignment.subject_id = new_subject.id
new_assignment.save
end
I'm going to make the assumption that your Subject has many Assignments, since you have a subject_id inside your Assignment class. If this is the case, the final and most correct way to write your loop would be:
old_subject.assignments.each do |assignment|
new_assignment = assignment.dup
new_assignment.subject_id = new_subject.id
new_assignment.save
end

Why is my Rails model custom setter/getter method failing?

what am I doing wrong here?
I have a model for an app I am writing called page. Those attributes are:
title
pagetype
page_url
title and pagetype can be set as normally, but I used a custom getter/setter for the page_url. Here is the logic/model:
class Page < ActiveRecord::Base
def page_url=()
temp = self[:title]
pageUrl = temp.gsub(" ", "_").downcase
if self[:pagetype] == "home"
pageUrl = "/"
end
self[:page_url] = pageUrl
end
def page_url
self[:page_url]
end
end
It's fairly simple -> page_url is based on the title with all spaces replaced with unless page_type == "home", which then gets set to "/". For the record I don't want to make page_url virtual because I need it to be searchable and saved in the db.
So unfortunately whether in rails console or my app this is failing. Here is how I am calling the setter method in the console;
page1 = Page.new
page1.pagetype = "home"
page1.title = "this is a test"
page2 = Page.new
pager2.pagetype = "content"
page2.title = "this is another test"
#expected results should be
page1.page_url()
=> "/"
page2.page_url()
However I keep getting this:
page1.page_url()
=> nil
What the heck am I doing wrong here?
These custom setter and getters don't persist to the database. If you have a column page_url in your database, you can set the value with a callback. E.g. before_save:
class Page < ActiveRecord::Base
before_save :set_page_url
def set_page_url
if self[:pagetype] == "home"
self.page_url = "/"
else
self.page_url = self[:title].gsub(" ", "_").downcase
end
end
end