activerecord

Should I include other fields in a HABTM table?

假装没事ソ 提交于 2019-12-08 22:13:33
I would like an Order object to be comprised of many Product objects, so I set up a HABTM relationship on object. I'm wondering if it's "correct" (or the Ruby/Rails) way to also include additional data within the HABTM table. For instance, if I need to compute the subtotal and there's a chance the line-item totals might need to be overridden, do I store that as part of the association table, or do I need a LineItem object or something better? Thanks ActiveRecord::Schema.define(version: 3) do create_table "orders", force: true do |t| t.string "order_id", null: false t.string "order_status",

Is it possible to ask for only certain columns from an ActiveRecord association?

落花浮王杯 提交于 2019-12-08 22:07:16
问题 consider def Foo has_one :user end let's say i only want a Foo 's User 's name, and not any of the other columns. so i want SELECT name FROM "users" WHERE "prices"."id" = 123 but doing foo.user.name will give me SELECT * FROM "users" WHERE "prices"."id" = 123 is there any slick way to use the association to get only one column? if not, then i have to do: User.where(id: foo.user_id).pluck(:name).first 回答1: In general you can specify what columns you want to select using the .select method,

Rails 3 ActiveRecord .skip_callback thread safety

百般思念 提交于 2019-12-08 22:04:43
问题 Is this code thread safe? MyModel.skip_callback(:save, :before, :my_callback) my_model_instance.update_attributes(attributes) MyModel.set_callback(:save, :before, :my_callback) Can i safely use it to avoid retrigger the same callback recursively? Here is an example class Blog < ActiveRecord::Base after_save :update_blog_theme, :if => :active_theme_id_changed? # ... private def update_blog_theme # Reuses a previously used BlogTheme or creates a new one blog_theme = BlogTheme.find_by_theme_id

Rails accepts_nested_attributes_for Error, please help me spot it

怎甘沉沦 提交于 2019-12-08 21:05:23
问题 I have been trying to follow the Active Record Nested Attributes Guide, without much success. I have the following models: class Contact < ActiveRecord::Base has_many :telephones accepts_nested_attributes_for :telephones end class Telephone < ActiveRecord::Base belongs_to :contact end When trying to create a contact: contact = { :name => "John", :telephones => [ {:telephone => '787445741'}, {:telephone => '478589658'} ] } Contact.create(contact) I get the following error: ActiveRecord:

validates :something, :confirmation => true & attr_accessor confusion

北城以北 提交于 2019-12-08 20:04:25
am struggling with Ruby validates :confirmation => true in my Rails app. Consider the following code: # == Schema Information # # Table name: things # # id :integer not null, primary key # pin :integer(8) # created_at :datetime # updated_at :datetime # class Things < ActiveRecord::Base #attr_accessor :pin attr_accessible :pin, :pin_confirmation validates :pin, :confirmation => true, :length => { :within => 7..15 }, :numericality => { :only_integer => true } end As the code is above, my validation works fine from the Rails console: 1.9.3-p0 :002 > l2 = Thing.create! :pin => 1234567, :pin

Rails ActiveRecord: Getting the id of a raw insert

北慕城南 提交于 2019-12-08 19:35:57
问题 sql = DmozCategory.send(:sanitize_sql_array, ["INSERT INTO dmoz_categories (id, dmoz_category_title, dmoz_category_name, dmoz_category_description, created_at, updated_at, dmoz_category_lastupdate) VALUES (?, ?, ?, ?, NOW(), NOW(), ?)", result['catid'], result['title'], result['name'], result['description'], result['lastupdate']]) res = DmozCategory.connection.execute(sql) $stderr.puts res.inspect res is always nil , even though I can see the DmozCategory inserts into the database. How to get

Can I convert model with one of its associations to YAML format?

心已入冬 提交于 2019-12-08 19:25:20
问题 I want to print ActiveRecord model in YAML format for debugging purposes. Currently I invoke model.to_yaml . But it doesn't return model's associations How can I convert model with one of its associations to YAML format? 回答1: You can convert to json first. The default ActiveRecord as_json method allows you to include assocations. From there, it's straightforward to convert to yaml. Example: menu.as_json(include: :dishes).to_yaml 回答2: to_yaml ignores the include-parameter ... but you could do

Rails 3 default scope, scope with override

霸气de小男生 提交于 2019-12-08 19:17:03
问题 I have a situation where the behavior of an existing app is changing and it's causing me a major headache. My app has Photos. Photos have a status: "batch", "queue", or "complete" . All the existing Photos in the app are "complete". 99% of the time I need to only show complete photos, and in all of the existing codebase I need every call to Photos to be limited to only complete photos. However, in the screens related to uploading and classifying photos I need to be able to fairly easily

Rails4 : Model caching (low level caching)

吃可爱长大的小学妹 提交于 2019-12-08 19:16:28
I am trying to cache results of Active Record Query. Here is my use case: User.rb def self.awesome_users_cached Rails.cache.fetch("awesome_users") { where(awesome: true) } end UsersController def index all_awesome_users = User.awesome_users_cached less_awesome_users = User.where(less_awesome_user:true).pluck(:id) @users = all_awesome_users.where.not(id: less_awesome_users) end Here are 2 issues: self.awesome_users_cached doesnt cache the results and ends up hitting the all_awesome_users ends up as an array instead of active Record and hence I cannot filter out less_awesome_users from it. There

Adding a column before another one in Rails

纵饮孤独 提交于 2019-12-08 18:58:56
问题 I'm looking to put a column at the front of my table I know you can do add_column :customer, :first_name, after: :last_name but is there a way to do :before ? 回答1: You're able to insert a column at the front of your table by using the :first option: add_column :table_name, :column_name, :column_type, first: true You can still use :after to handle all other positioning cases. 回答2: These are mysql-specific options by the way. https://github.com/rails/rails/blob/80e66cc/activerecord/lib/active