1
我試圖解決Rails的問題。這是我的第一個Rails應用程序,我正在對我們未來的項目進行評估。我一直跟隨railstutorial.org一直到第9章,然後試圖自己去做。Rspec和工廠女孩的Rails麻煩
使用Rails 3.2.3,Ruby 1.9.3,Factory Girl 1.4.0和rspec 2.10.0。
我遇到的麻煩是客戶端 - [has_many] - >用戶關係。
運行測試時我不能獲得通過的錯誤:
1) User
Failure/Error: let(:client) { FactoryGirl.create(:client) }
NoMethodError:
undefined method `user' for #<Client:0x000000045cbfa8>
規格/ factories.rb
FactoryGirl.define do
factory :client do
sequence(:company_name) { |n| "Company #{n}" }
sequence(:address) { |n| "#{n} Example Street"}
phone "0-123-456-7890"
end
factory :user do
sequence(:name) { |n| "Person #{n}" }
sequence(:email) { |n| "person_#{n}@example.com"}
password "foobar"
password_confirmation "foobar"
client
factory :admin do
admin true
end
end
規格/型號/ user_spec.rb
require 'spec_helper'
describe User do
let(:client) { FactoryGirl.create(:client) }
before { @user = client.users.build(name: "Example User",
email: "[email protected]",
password: "foobar",
password_confirmation: "foobar") }
subject { @user }
it { should respond_to(:name) }
end
應用/controllers/clients_controller.rb
class ClientsController < ApplicationController
def show
@client = Client.find(params[:id])
end
def new
@client = Client.new
@client.users.build # Initializes an empty user to be used on new form
end
def create
@client = Client.new(params[:client])
if @client.save
flash[:success] = "Welcome!"
redirect_to @client
else
render 'new'
end
end
end
應用程序/控制器/ users_controller.rb
class UsersController < ApplicationController
.
.
.
def new
@user = User.new
end
.
.
.
end
應用程序/模型/ user.rb
class User < ActiveRecord::Base
belongs_to :client
.
.
.
end
應用程序/模型/ client.rb
class Client < ActiveRecord::Base
has_many :users, dependent: :destroy
.
.
.
end
感謝您的幫助!
實際上,用戶應該屬於客戶端,客戶端有很多用戶。我將用我的模型更新這個問題。也許我有點搞砸那裏的協會... – IanBussieres
謝謝@Mori。我已經更新了我的模型。我不確定您的解決方案是否仍然適用。我真的希望這種關係成爲客戶端 - [has_many] - >用戶,因此,用戶 - [belongs_to] - >客戶端 – IanBussieres
原來在模型中有一個被遺忘的行,確實重新定義了:user屬性客戶。謝謝。 – IanBussieres