0

When I invite a user in my Rails 4 app using devise-invitable, a new friendly id is not created by the app. I have the following code in my user.rb file

extend FriendlyId
friendly_id :name, :use => :slugged
def should_generate_new_friendly_id?
  after_invite_path_for? || new_record? || name_changed? || slug.blank? || super
end

I've tried quite a few different options but can't seem to figure it out

David Mckee
  • 1,100
  • 3
  • 19
  • 35

3 Answers3

0

Assuming you are collecting your invitees name during the invitation acceptance process, this can be achieved by adding this to your controller:

Application Controller

before_filter :configure_permitted_parameters, if: :devise_controller?

protected

def configure_permitted_parameters    
   devise_parameter_sanitizer.for(:accept_invitation).concat([:name, :slug])
end
RubyNewbie
  • 547
  • 5
  • 21
0

If you ment you want to create the slug when creating an invite:

I've encountered the same problem.

the command i use to invite a user:
User.invite!(email: "example@email.com", name: "John John")

the problem is that for some reason the should_generate_new_friendly_id? is not called in this proccess.

my solution was to write a method to create the user slug

def slug_me!
  new_slug = [name.parameterize].join("-")
  if User.where(slug: new_slug).present? #check if the is a user with that slug already
    new_slug = [name.parameterize, User.last.id+1].join("-")
  end
  update_column(:slug, new_slug)
end

(in my app the new_slag will be unique. not sure about your app. you might need to change [name.parameterize, User.last.id+1].join("-") to something else that will fit your needs)

and override the invite! method that devise uses:

def invite!
  super
  slug_me! if should_generate_new_friendly_id?
end

(i've added if should_generate_new_friendly_id? so it wont create a slug if you invite the same person more then once)

in this case should_generate_new_friendly_id? will return true because slug is nil so slug.blank? will return true

its might not be the best solution, but it works for me. (and im still looking for a better solution)

Ziv Galili
  • 1,405
  • 16
  • 20
  • FriendlyId has a private method `set_slug`--better to use that imo than reimplementing all the logic. You can call it with `user.send(:set_slug)` or just `send(:set_slug)` if you're inside the model. Note this doesn't save the record--I'm calling `user.save(validate: false)` after `set_slug` to save, but your use case may be different. And as with using any private method, make sure you have a test covering this so you'll catch it if FriendlyId changes their implementation in the future. – Dane Mar 13 '17 at 18:23
0

I faced the same problem on:

User.invite!(email: "example@email.com", name: "John John")

My solution was:

before_invitation_created :generate_slug

private

  def generate_slug
    return unless slug.nil?

    self.slug = set_slug
  end
Aya Sakr
  • 21
  • 2