I am following along with this Railscast for jQuery Tokeninput and everything is working. My only problem is that I need to figure out how to save a user id for a category upon creation. How can I save it within this code?

Model

class Category < ActiveRecord::Base
  belongs_to :user
  has_and_belongs_to_many :entries

  validates :name, :user_id, presence: true

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

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

Controller

def index
    @categories = Category.order(:name)
    respond_to do |format|
        format.html
        format.json { render json: @categories.tokens(params[:q]) }
    end
  end
有帮助吗?

解决方案

As we talked about, earlier. You can use http://rails-bestpractices.com/posts/47-fetch-current-user-in-models to access the current_user inside of the model.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top