我正在尝试在导入的列表中设置外键。我的想法是创建一个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
答案 0 :(得分:0)
您可以先找到餐厅,然后将联系人添加到餐厅联系人处。
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)
restaurant = Restaurant.find_by_id(r_id) # Get the restaurant here
restaurant.contacts << contact # This will do a save immediately
end
end