Rails generate slug before saving based on other field -


I have a site with model name and slug The parameter protects the user every time I change the site , but if slug wants to be unique, then the rail app will want to generate specialty to ensure the specificity. I have a validation for.

The challenge I have is that when a user creates another site with the same name, then a similar slug is generated. Like name = "hello and name =" hElLo " both hello

  generated before_validation: create_slug personal def Create_slug self.slug = self.name.parameterize end  

I tried to add a time loop, which was a site with a single slug or not, and as long as Each loop "1" was unique. The problem is that if I update a site then it will be loop that a site with the same slug is in existence, and to increase the slug, Lake The site that already exists was the same site.

Here's the code:

  def create_slug a = self.name.parameterize while site.where (Slug: a). Count> 0 do a = a + "-1" Finally I think you can solve your problem in two steps. Ie, i.ic.  

Firstly by refining your first_filter conditional one, avoid always avoidance

  before_value Idation: create_slug if :: name_changed?  

In this way, callback only Will be executed only when the name field is updated Will.

The second name code> verifier so that instead of using the default specificity variant provided by the rail, or to move the verification of the slug field Rather than what it really is necessary for you.


Comments

Popular posts from this blog

import - Python ImportError: No module named wmi -

Editing Python Class in Shell and SQLAlchemy -

c# - MySQL Parameterized Select Query joining tables issue -