インポートされたリストに外部キーを設定しようとしています。私の考えは、セッション変数を使用して外部キーを更新する before_save コールバックを作成することでした。ただし、モデルからセッション変数に簡単にアクセスできない、またはアクセスすべきではないというのが私の理解です。その場合、他にどのような選択肢がありますか。私のコードは次のとおりです。
モデルでは:
class Contact < ActiveRecord::Base
   attr_accessible :first_name, :last_name, :email, :mobile, :restaurant _id
   belongs_to :restaurant
    before_save :add_restaurant
    def add_restaurant
     contact = Contact.find_by_restaurant_id(session[:current_restaurant])
     contact.restaurant_id = (session[:current_restaurant])
    end
  def self.import(file)
    CSV.foreach(file.path, headers: true) do |row|
    contact = find_by_first_name_and_last_name(row["first_name"], row["last_name"]) || new
    contact.attributes = row.to_hash.slice(*accessible_attributes)
    contact.save!
    end
  end
end
コントローラーで:
def import
    Contact.import(params[:file])
    redirect_to contacts_path, notice: "List imported"
end