gjenskapelse
gjenskapelse

Reputation: 69

tokeninput with rails 4, not inserting

So been racking this all day long and my search works fine now, but I can't seem to insert anything new. I tried strong params already and no dice.

Does anyone have experience with token input and had custom primary_keys?

and how does this code work specifically?

  def self.tokens(query)
    cooking_types = where("lower(cooking_style) ILIKE ?", "%#{query}%")
    if cooking_types.empty?
        [{id: "<<<#{query}>>>", name: "New: \"#{query}\""}]
    else
        cooking_types
    end
  end


  def self.ids_from_tokens(tokens)
    tokens.gsub!(/<<<(.+?)>>>/) { create!(name: $1).id }
    tokens.split(',')
  end


  def cooking_type_tokens=(tokens)
    self.cooking_type_ids = CookingType.ids_from_tokens(tokens)
  end

Upvotes: 0

Views: 96

Answers (1)

gjenskapelse
gjenskapelse

Reputation: 69

params.require(:restaurant).permit(some attributes...., :cooking_type_id)

Someone posted a solution on the railscast that the parameter should be passed into an array, but it didn't work for me so I just did it as a regular variable (since it's already an array). Also, look at the method for collecting the tokens, I changed it to reflect the parameter being passed. I also want to note that the cooking_type_id is exactly the name of the field as well to the child model.

 def cooking_type_id=(tokens)
    self.cooking_type_ids = CookingType.ids_from_tokens(tokens)
 end

Let me know if you need more help! It's finally nice to help someone out after all my asking.

 def self.ids_from_tokens(tokens)
    tokens.gsub!(/<<<(.+?)>>>/) { create!(name: $1).id }
    tokens.split(',')
  end

This code simple takes all the tokens id and creates a new entry if you're searching for something that's not in your child model.

Upvotes: 1

Related Questions