text
stringlengths
10
2.61M
# Controlador Medicos # Acciones index, detalles, nuevo, crear, borrar class MedicosController < ApplicationController def index @q = Medico.ransack(params[:q]) @medicos = @q.result(distict: true).paginate(page: params[:page]) end def detalles @medico = Medico.find(params[:id]) end def nuevo ...
class Company < ActiveRecord::Base validates :name, :city, presence: true validates :name, uniqueness: true has_many :jobs, dependent: :destroy has_many :comments, dependent: :destroy has_many :contacts, dependent: :destroy def self.top_three top = Job.group(:company_id).average(:level_of_interest) ...
class RoutesController < ApplicationController before_filter :logged_in_user, :only => [:new, :create, :edit, :update, :destroy] layout "flight_log/flight_log" add_breadcrumb 'Home', 'flightlog_path' def index add_breadcrumb 'Routes', 'routes_path' @title = "Routes" @meta_description = "A list of...
class VantagemsController < ApplicationController before_action :set_vantagem, only: [:show, :edit, :update, :destroy] # GET /vantagem # GET /vantagems.json def index @vantagems = Vantagem.all end # GET /vantagems/1 # GET /vantagems/1.json def show end # GET /vantagems/new def new @vant...
# frozen_string_literal: true class DrawerComponent < ViewComponent::Base def initialize(current_user:) @current_user = current_user end def user_image helpers.current_user_image end def current_user_path user_path(@current_user) end def current_user_email @current_user.email end end...
class CreateTeamTasks < ActiveRecord::Migration[4.2] def change create_table :team_tasks do |t| t.string :label, null: false t.string :task_type, null: false t.text :description t.text :options t.text :project_ids t.text :mapping t.boolean :required, default: false ...
class CartItem < ApplicationRecord belongs_to :customer belongs_to :item validates :amount, presence: true def total_price (item.add_tax_price * amount) * 1.1.round end def self.sum_price sum {|cart_item| cart_item.total_price} end def self.total_payment sum {|cart_item| cart_item.total_...
class Attendance < ActiveRecord::Base validates_presence_of :student_id validates_presence_of :attendance validates_presence_of :Date belongs_to :student end
class Part < ApplicationRecord has_and_belongs_to_many :car validates :name, presence: true, uniqueness: true end
# # Copyright (c) 2013, 2021, Oracle and/or its affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
# frozen_string_literal: true require 'rails_helper' RSpec.describe ContractsController, type: :controller do describe '#index' do let(:user) { FactoryBot.create(:user) } let!(:user_contract) { FactoryBot.create(:contract, user: user) } let!(:another_contract) { FactoryBot.create(:contract) } conte...
class WelcomeController < ApplicationController def home @welcome_text = Page.try(:first).try(:content) end end
require 'vizier/executable_unit' module Vizier class TaskList def initialize(*task_lists) @tasks = [] task_lists.each do |list| list.each do |task| unless @tasks.include?(task) @tasks << task end end end end def executable? !@tasks....
class PetController < ApplicationController before_action :authorize, only: [:index, :show, :delete, :create, :edit, :new, :update, :destroy] def new @pet = Pet.new end def create @pet = Pet.new(pet_params) if @pet.save redirect_to controller: 'pet', action: 'index', dni: pet_params[:owner] else ren...
describe "merb-cache-page" do it "should cache page (action5)" do c = get("/cache_controller/action5") c.body.strip.should == "test action5" c.cached_page?("action5").should be_true end it "should expire page (action5)" do CACHE.expire_page("action5") CACHE.cached_page?("action5").should be_...
class GPXstatsmodel attr_accessor :distance attr_accessor :duration_s attr_accessor :speed_avg attr_accessor :elevation_diff attr_accessor :hr_max attr_accessor :hr_avg def initialize(distance, duration_s, speed_avg, speed_max, elevation_max, elevation_min, ele_diff, hr_min, hr_max, hr_avg) @distance = distance...
# Usage: rake givdo:assign_orgs # NOTE: Will assign first organization to all Users and Players. namespace :givdo do desc "Assign organizations to users" task :assign_orgs => :environment do User.where(organization_id: nil).update_all(organization_id: Organization.first.id) Player.where(organization_id: nil...
require 'colorize' class Simon COLORS = %w(red blue green yellow) attr_accessor :sequence_length, :game_over, :seq def initialize @sequence_length = 1 @game_over = false @seq = [] end def play system("clear") puts "Hello and, again, welcome to the App Academy computer-aided enrichment ...
class MEncrypt < ActiveRecord::Base self.table_name = "m_encrypts" self.primary_key = :encrypt_id # encrypt_id, encryption_type, file_name, created_by, updated_by, # created_at, updated_at, username, hashed_key, :encrypted_key validates_uniqueness_of :encrypt_id validates_presence_of :encrypt_id, :e...
# for order controller class OrdersController < ApplicationController before_action :set_order, only: [:show, :edit, :update, :destroy, :purchase] # GET /orders # GET /orders.json def index @q = Order.order(id: :desc).search(params[:q]) @orders = @q.result.includes(:user).page(params[:page]).per(20) ...
# encoding: utf-8 control "V-52273" do title "The DBMS must support organizational requirements to prohibit password reuse for the organization-defined number of generations." desc "Password complexity, or strength, is a measure of the effectiveness of a password in resisting attempts at guessing and brute-force att...
class InventorySnapshotSerializer < ActiveModel::Serializer self.root = false attributes :user_attributes, :has_active_subscription, :last_subscription_expiry, :purchases has_many :items def purchases object.attributes['in_app_purchases'] || 0 end def has_active_subscription object.subscription...
class EricWeixin::Cms::Weixin::MediaNewsController < EricWeixin::Cms::BaseController def index end def new end def query_media_articles @media_articles = ::EricWeixin::MediaArticle.common_query params.permit(:tag, :start_date, :end_date, :public_account_id) @total_page = (@media_articles.count/4) ...
class Day < ApplicationRecord has_many :daily_habits has_many :habits, through: :daily_habits end
class Product < ActiveRecord::Base validates:description, presence:true validates:deadline, presence:true validates:user_id, presence:true belongs_to :user has_many :bids end
class TuftsImageText < TuftsBase has_file_datastream 'Content.html', control_group: 'E' has_file_datastream 'Thumbnail.png', control_group: 'E' has_file_datastream 'Archival.tif', control_group: 'E' has_file_datastream 'Advanced.jpg', control_group: 'E' has_file_datastream 'Basic.jpg', control_group: 'E' d...
class AddFavouriteToOrigami < ActiveRecord::Migration[5.1] def change add_column :origamis, :favourite, :boolean, default: false end end
# begin to build a simple program that models Instagram # you should have a User class, a Photo class and a comment class require "pry" class User attr_accessor :name, :photo, :comments @@all = [] def initialize(name) @name = name @@all << self end def self.all @@all end def photos Phot...
class User < ActiveRecord::Base INDUSTRIES = ['General', 'Accounting/Bookkeeping/Tax Prep', 'Advertising/Marketing/PR', 'Architecture/Interior Design', 'Automotive', 'Business/Trade/Networking Organization', 'Banking/Finance', 'Business Consulting', 'Construction/Contracting', 'Design/Creative Services', 'Education'...
# frozen_string_literal: true require 'rails_helper' RSpec.describe OrdersController, type: :controller do describe 'GET /orders' do let(:response_api) { { 'list' => { 'orders' => 'orders' } } } before do allow_any_instance_of(Pitzi::Orders).to receive(:list).and_return(response_api) end it ...
require 'rails_helper' RSpec.describe Request, type: :model do before { @request = FactoryGirl.build :request } subject { @request } it { should be_valid } @request_attributes = [:fullname, :phonenumber, :email, :company, :job_title, :contacted, :accepted_offer] # model should respond to attributes @...
class SubjectsController < ApplicationController load_resource def index @subjects = Subject.all respond_to do |format| format.html format.js end end def show @subject = Subject.find(params[:id]) end def new @subject = Subject.new respond_to do |format| format.js ...
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_secure_token :auth_token has_many :orders has_...
module Codegrade class Formatter def initialize(offenses) @offenses = offenses end def print group_by_files working_directory = File.expand_path('.') @categories.each do |category, offenses| puts "#{category} (#{offenses.size}):" puts offenses.each do |of...
require 'rails_helper' feature 'User tries to login with steam' do before do # Disable news feed Rails.configuration.news['type'] = 'none' end scenario 'for the first time' do visit teams_path OmniAuth.mock_auth_hash(name: 'Kenneth') find('#login').click expect(current_url).to eq(new_u...
json.array!(@organizations) do |organization| json.extract! organization, :id, :name, :email, :slogan, :mission, :vision, :phone, :status json.url organization_url(organization, format: :json) end
FactoryGirl.define do factory :customer do first_name { Faker::Name.first_name } last_name { Faker::Name.last_name } created_at { Faker::Time.between(DateTime.now - 5, DateTime.now - 2) } updated_at { Faker::Time.between(DateTime.now - 2, DateTime.now) } end factory :item do name { Faker::Com...
Write a method that takes two Array arguments in which each Array contains a list of numbers, and returns a new Array that contains the product of each pair of numbers from the arguments that have the same index. You may assume that the arguments contain the same number of elements. Examples: multiply_list([3, 5, 7]...
require 'net/http' require 'json' # Using URI and Net:HTTP which are already included with Rails uri = URI('https://urlxray.expeditedaddons.com') # Change the input parameters here uri.query = URI.encode_www_form({ api_key: 'DG3R6H4UL3E9JSY72XP0KC891ZWB16057T84NIOVFAMQ25', url: 'http://www.forexarena.com', fet...
require_relative 'piece' require_relative 'stepping' class Rook < Piece include Sliding def initialize super @first_move = true end def to_s if color == :white " ♟ " else " ♙ " end end def specific_moves new_moves = [] if color == :white if @first_move ...
# encoding: utf-8 class InstallationPurchasesController < ApplicationController before_filter :require_signin before_filter :require_employee before_filter :load_installation helper_method :has_show_right?, :has_create_right?, :has_update_right?, :has_log_right?, :need_approve?, :has_warehousing_right? ...
#!/usr/bin/env ruby require 'digest' require 'thor' require 'fuzzy_match' require 'launchy' require 'coursesdesc' # for production # require '../lib/coursesdesc/courses.rb' # for cmd line testing purposes class KiwiCLI < Thor desc 'search COURSENAME', 'Search a course on ShareCourse' def search(coursename) sc ...
# frozen_string_literal: true class FinancialEntry < ApplicationRecord belongs_to :user validates :content_file, presence: true end
require 'spec/rack_helper' describe Avito::API::V1::Users, type: :controller do let(:user) { Fabricate :user } describe 'GET /v1/users/:id' do subject { get "/api/v1/users/#{user.id}" } context 'with authenticated user' do login_user it { is_expected.to be_ok } it { is_expected.to match...
class RemoveColumnFromUsersAddToCampaign < ActiveRecord::Migration def change remove_column :users, :donation_alerts add_column :campaigns, :donation_alerts, :boolean end end
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2019-2020 MongoDB Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # U...
require 'rails_helper' RSpec.describe User, type: :model do let(:admin) { build(:admin) } include_examples "create models" describe "Model" do it 'has an email' do expect(user.email).to eq("tom_example@yahoo.com") end it 'has a first name' do expect(user.first_name).to eq("Tom") ...
class BaseService attr_reader :data def self.call(*args) new(*args).call end def call payload self end def success? errors.empty? end def errors @errors ||= ActiveModel::Errors.new(self) end end
# frozen_string_literal: true class ApplicationController < ActionController::Base include Pundit before_action :authenticate_user!, except: :health def append_info_to_payload(payload) super payload[:user_email] = current_user.try :email end def health conn = ActiveRecord::Base.connection.raw_c...
class MealPlansController < ApplicationController before_action :set_meal_plan, only: [:edit, :update, :destroy, :replace_meal] # before_action :authenticate_user! def show @mealplan = MealPlan.find(params[:id]) meals = @mealplan.daily_meals end def try_out_mealplan ########################...
class CardsetsController < ApplicationController before_action :signed_in_user, only: [:new, :create, :edit, :update, :destroy] before_action :correct_user, only: [:edit, :update, :destroy] def index @cardsets = Cardset.all end def new @cardset = Cardset.new end def create @cardset = Cardse...
#!/usr/bin/env ruby # Usage: hr otd # Summary: Print a random event that happened on this day in history, courtesy # of Wikipedia. require 'nokogiri' require 'open-uri' def todays_url todays_date = Time.now.strftime("%B_%-e") "https://en.wikipedia.org/wiki/#{todays_date}" end def events Nokogiri::HTML(open(toda...
require 'spec_helper' describe ActivityCreator, '#post' do include DelayedJobSpecHelper it 'posts to the Yammer API on post' do Yam.stubs(:post) user = build_user action = 'vote' event = build_stubbed(:event_with_invitees) ActivityCreator.new(user: user, action: action, event: event).post ...
class AddPageFaqsCountToFaqs < ActiveRecord::Migration def change add_column :faqs, :page_faqs_count, :integer, default: 0 Faq.reset_column_information Faq.find(:all).each do |p| Faq.update_counters p.id, page_faqs_count: p.page_faqs.length end end end
# == Schema Information # # Table name: events # # id :integer not null, primary key # title :string # description :string # caption :string # event_date :datetime # timeline_id :integer # created_at :datetime not null # updated_at :datetime not null # require 'ra...
require 'json' require_relative 'base_reddit' require_relative 'user_comment' require_relative 'user_submission' class User < BaseReddit attr_accessor :name, :metadata, :submissions_ended_at, :submissions_after attr_accessor :comments_ended_at, :comments_after, :reddit_object attr_accessor :comments, :submission...
name 'nginx_sinatra' maintainer 'amazedkoumei' maintainer_email 'amazed.koumei@gmail.com' license 'All rights reserved' description 'Installs/Configures sinatra' version '0.1.0'
class RenameConsumerUserFavourite < ActiveRecord::Migration def change rename_column :favourites, :consumer_id, :user_id end end
require 'friendly/scope' module Friendly class NamedScope attr_reader :klass, :parameters, :scope_klass def initialize(klass, parameters, scope_klass = Scope) @klass = klass @parameters = parameters @scope_klass = scope_klass end def scope @scope_klass.new(@klass, @pa...
module TutorialsHelper VIDEO_HEIGHT = 450 VIDEO_WIDTH = 800 def tag_cloud(tags, classes) max = tags.sort_by(&:count).last tags.each do |tag| index = tag.count.to_f / max.count * (classes.size-1) yield(tag, classes[index.round]) end end def user_id(id) ...
class MessagesController < ApplicationController def index @messages = Message.all end def new @message = Message.new end def create @message = Message.new(message_params) if @message.save redirect_to '/messages' else render 'new' end end def show @message = Message.find(params[:id]) en...
require_relative "../hotness.rb" describe Hotness do before do class Image include Hotness end @image = Image.new end it "should return a start date" do aug_13 = Time.local(2014, 8, 13) expect(Hotness::START_DATE).to eq(aug_13) end it "#seconds_from_start_time should return seconds from a given ti...
people = 30 cars = 40 trucks = 15 #if, elsif, and else functions. #In this case, cars are greater than people so the first if statement will be printed. if cars > people puts "We should take the cars." elsif cars < people puts "We should not take the cars." else puts "We can't decide." end #if elsif and else st...
module Meiosis class Transaction attr_accessor :inputs, :outputs, :deps, :version, :fee, :input_sig, :hash attr_reader :serialized_self, :status # @inputs array of cell outpoints # @outputs array of <Cell> instances def initialize(version=0, inputs=[], outputs=[], deps=[Meiosis::Config.api.system_...
class AddRatingEvent < ActiveRecord::Migration def self.up add_column :events, :rating, :float, :default => 0, :null => false add_column :events, :rated_count, :integer, :default => 0, :null => false end def self.down remove_column :events, :rating remove_column :events, :rated_count end end
class User < ActiveRecord::Base attr_accessible :birthday, :email, :first_name, :login, :middle_name, :password, :second_name validates :password, presence: true, length: {in: 5..32} validates :login, presence: true, uniqueness: true end
# Encoding: UTF-8 require 'test_helper' require 'traject/indexer' # should be built into every indexer describe "Traject::Macros::Transformation" do before do @indexer = Traject::Indexer.new @record = nil end describe "translation_map" do it "translates" do @indexer.configure do to_fi...
class StorageEntry < ActiveRecord::Base scope :by_reason, lambda{|reason_id| where(storage_entry_type_id: reason_id)} scope :by_product, lambda {|product_id| where(product_id: product_id)} scope :by_movement_date, lambda { |min_date, max_date| where('storage_entries.movement_date >= ? and storage_entries.move...
require 'rspec' require_relative '../model/CalculadoraFactoresPrimos' describe 'CalculadoraFactoresPrimosTest' do let(:calculadora) { CalculadoraFactoresPrimos.new } begin it 'primos de 4 son 2 y 2' do expect(calculadora.calcular("4")).to eq([2, 2]) end it 'primos de 360 son 2, 2, 2, 3, 3 y...
class CreateCommands < ActiveRecord::Migration def change create_table :commands do |t| t.datetime :date, null: false t.string :description, null: false t.datetime :limit_date t.string :payment t.string :state, null: false t.decimal :total, precision: 8, scale: 2 t.times...
class ApplicationController < ActionController::Base KEYS_FLASH = %i[error warning success info] protect_from_forgery with: :exception include SessionsHelper before_action :authenticate_user def authenticate_user return if signed_in? display_flash(:error, 'You are not signed in.') redirect_to...
class User < ActiveRecord::Base has_secure_password validates :name, presence: true validates :email, presence: true, uniqueness: true validates :password, presence: true, confirmation: true, length: { minimum: 8} def self.authenticate_with_credentials(email, password) user = User.find_by(email: emai...
module WelcomeHelper def resource @company ||= Company.new end def resource_name :company end def registration_path(resource_name) company_registration_path end def devise_mapping @devise_mapping ||= Devise.mappings[:company] end end
class RenameOrderItemsToReservations < ActiveRecord::Migration def change rename_table :order_items, :reservations end end
module StorePages def self.included(klass) if klass.respond_to? :helper_method klass.helper_method :is_store? klass.helper_method :news_enabled? klass.helper_method :events_enabled? klass.helper_method :twitter_enabled? klass.helper 'mysears/mystore' end end def...
module Decidim module Participations module Admin class UpdateParticipation < Rectify::Command # Public: Initializes the command. # # form - A form object with the params. # current_user - The current user. # current_participatory_process - The current partici...
cask :v1 => 'openscad' do version '2014.03' sha256 'c324c19c2d36f21517b602f8ae2ec04fa14c90896c91fc8dbb37aed5b3ba16bd' url "http://files.openscad.org/OpenSCAD-#{version}.dmg" name 'OpenSCAD' homepage 'http://www.openscad.org/' license :gpl app 'OpenSCAD.app' end
class WorksController < ApplicationController # Only allow logged in users to access certain pages before_action :logged_in_user, only: [:new, :create, :edit, :update] # Only allow the original user or admin to perform certain actions before_action :check_work_user, only: [:edit, :update, :destroy] # Displa...
require('rspec') require('numbers_to_words') describe("Fixnum#numbers_to_words") do it("translates single digit numbers in numeric form into a written word") do expect(1.numbers_to_words()).to(eq("one")) end it("translates numbers less than twenty in numeric form into a written word") do expect(12.numbers_t...
class ProcessSanityGenerator < Rails::Generators::Base source_root File.expand_path("../templates", __FILE__) def create_initializer_file copy_file "process_sanity.rb", "config/initializers/process_sanity.rb" end end
class PropertiesController < ApplicationController caches_page :index, if: lambda { |controller| controller.request.xhr? ? false : true } def index @title = "househappy.org" @properties = Property.includes(:neighborhood, :photos).active @properties = @properties.price_lt(params[:price_lt]) if param...
# coding: utf-8 $:.unshift File.expand_path('../lib', __FILE__) require 'vagrant-netinfo/version' Gem::Specification.new do |spec| spec.name = 'vagrant-netinfo' spec.version = VagrantPlugins::Netinfo::VERSION spec.authors = ['Jan Vansteenkiste'] spec.email = ['jan@vstone.eu'] ...
class LinkApplicationsToClients < ActiveRecord::Migration def up add_column :applications, :client_id, :integer end def down remove_column :applications, :client_id end end
class Task < ApplicationRecord belongs_to :user has_many :label_attached_tasks, dependent: :destroy has_many :task_labels, through: :label_attached_tasks validates :title, presence: true, length: { maximum: 30 } validates :description, length: { maximum: 100 } validate :deadline_is_not_past enum status:...
#!/usr/bin/ruby # This script generates the GERALD command that can be used to create GERALD # directory in the in the flowcell to analyze require 'fileutils' require 'PipelineHelper' require 'ExptDir' class BuildGERALDCommand def initialize(fcName, laneBarcode) # @pipelinePath = "/stornext/snfs5/next-gen/Illumin...
class ChangeColumnsOrderOnPosts < ActiveRecord::Migration def change change_column :posts, :topic, :string, after: :user_id change_column :posts, :content, :string, after: :topic end end
=begin + Создать модуль InstanceCounter, содержащий следующие методы класса и инстанс-методы, которые подключаются автоматически при вызове include в классе: - Методы класса: - instances, который возвращает кол-во экземпляров данного класса - Инстанс-методы: - register_instance, который увеличивает с...
require 'active_support/inflector' require './connection_adapter/column.rb' require './simple_record.rb' class WhereClause def initialize(table_name, col_definitions, primary_key) @col_definitions = col_definitions @table_name = table_name @primary_key = primary_key @value = '' end def build(col...
# Controlador Pacientes # Acciones index, detalles, nuevo, crear, borrar class PacientesController < ApplicationController def index @q = Paciente.ransack(params[:q]) @pacientes = @q.result(distict: true).paginate(page: params[:page]) end def detalles @paciente = Paciente.find(params[:id]) end ...
require 'spec_helper' describe Page do it { should validate_presence_of :body } it { should validate_presence_of :title } it { should validate_presence_of :page_img_url } it { should validate_presence_of :page_name } it { should allow_mass_assignment_of :body } it { should allow_mass_assignment_of :t...
class Collect < ApplicationRecord belongs_to :custom_collection belongs_to :product validates :position, :sort_value, presence: true validates :sort_value, allow_nil: true, length: { maximum: 10 } end
require 'text_analysis/tokenizer.rb' class BooksController < ApplicationController layout :resolve_layout def open redirect_to root_url if !params[:id] and !/^[0-9]+$/.match(params[:id]) @b = Book.find(params[:id]) redirect_to read_book_path(@b.id) end def request_partial book_id = params[:id...
json.array!(@student_applications) do |student_application| json.extract! student_application, :id, :student_id, :name, :phone, :email_id, :gpa json.url student_application_url(student_application, format: :json) end
class Contacto < ActiveRecord::Base validates :correo, presence: {message: "El campo correo no debe de estar vacio"} end
# Write a program called name.rb that asks the user to type in their name and then prints out a greeting message with their name included. puts "Give me your name forever!" name = gets.chomp puts "#{name} is mine forever!" # Add another section onto name.rb that prints the name of the user 10 times. You must do this...
class Paradigm < ActiveRecord::Base #Relationships has_many :resources, :dependent => :destroy # Validations validates_presence_of :name, :description, :ranking validates_numericality_of :ranking, only_integer: true validates_uniqueness_of :ranking, :name # Scopes scope :alphabetical, -> { order("nam...
class GoogleCalendarReminder < ApplicationRecord belongs_to :google_calendar scope :ready, -> { where(announced: false).where('remind_at < NOW()') } scope :upcoming, -> { where('remind_at > NOW()') } def announce return if announced? SpeechEngine.say(content, volume: 100) update_attribute :announc...
require './sales_calculator' RSpec.configure do |config| config.mock_framework = :mocha end describe SalesCalculator do let(:klass) { SalesCalculator } describe 'calculations' do describe 'SalesCalculator::NEXT_FREE' do # Original price is set to 2$ # Sale will be applied on each second product...
class CoachesController < ApplicationController before_action :validate_admin # 教练列表首页 def index @coaches = User.coaches.order("updated_at desc") end def search end # 添加教练 def new end # 创建教练 def create User.transaction do coach = User.create(post_params) coach.add_coach ...
class Song < ActiveRecord::Base attr_accessible :album_id, :title has_one :artist, :through => :album belongs_to :album end