On Dec 13, 6:07 pm, mwlang88 <[email protected]> wrote:
> So, here's the Chicken and Egg problem:
>
> I am trying to assign the generated slug for the page to a
> pages::slug_id column so that I have quick, direct access to the slug
> that is the one to be used to generate URLs in the CMS when rendering
> links to the page.
>
> I cannot associate a slug to a page until after the page has been
> saved and an ID for the page is known.  Thus, I cannot associate the
> slug to the page in the before_save, after_create, or after_initialize
> callbacks.

I would think it possible to create it in an after_save callback:

class Slug
  def page_name=(s)
    self.name = s.gsub(/[^- \w]/, '').gsub(' ', '-').downcase
  end
end

class Page
  def after_save
    super
    update(:slug_id => add_slug(:page_name=>name).id) unless slug_id
  end
end

> If I try to associate the slug to the page in the page's after_save
> callback, then the slug_id for the page doesn't get populated with the
> slug record's id.

The above should work, though it requires a separate update query
after the insert.

> This is my two models:
>
> class Page < Sequel::Model
>   many_to_one :slug
> end
>
> class Slug < Sequel::Model
>    many_to_one :page
> end
>
> Ideally, I would like to do something like the following:
>
> new_page = Page.new(:name => "Michael's Awesome Home Page")
> new_page.add_slug("index.html)

You can't do the add_slug until after the object is saved, because it
requires the page's id.  You can use the instance hooks plugin:

  Page.plugin :instance_hooks
  new_page.after_save_hook{new_page.add_slug(:name=>'index.html')}

> new_page.save
> and have:
>
> Page.first  ==>
>    :id => 1
>    :name => "Michael's Awesome Home Page"
>    :slug_id => 1
>
> Slug.first ==>
>    :id => 1
>    :page_id => 1
>    :name => 'michaels-awesome-home-page'
>
> Slug.last ==>
>    :id => 2
>    :page_id => 1
>    :name => 'index.html'

This result should be possible using code similar to what I've shown
above.

Jeremy

--

You received this message because you are subscribed to the Google Groups 
"sequel-talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/sequel-talk?hl=en.


Reply via email to