rad*_*edo 5 parameters ruby-on-rails
显然我对铁轨很新,所以坚持下去.
我在我的模型中添加了一个构造函数
class Movie < Media
attr_accessible :director, :studio
attr_accessor :director, :studio
validates_presence_of :director, :studio, :title
def initialize title, director, studio
@title = title
@director = director
@studio = studio
end
end
Run Code Online (Sandbox Code Playgroud)
那种搞砸了我的东西.因为我在我的控制器中有一个方法'new'就像这样
def new
@movies = Movie.new
end
Run Code Online (Sandbox Code Playgroud)
并且在初始化出现之前它工作得很好.它需要将参数传递给'new'方法,但这是在视图打开后从用户传递参数并保存它们时完成的.现在我无法打开该视图,因为我收到错误
wrong number of arguments (0 for 3)
Run Code Online (Sandbox Code Playgroud)
添加构造函数是因为我开始为我的应用程序编写测试,并且为构造函数设置默认值会使该测试无效.解决这个问题的建议?
编辑:我的测试看起来像这样:
require 'spec_helper'
describe Movie do
before :each do
@movie = Movie.new "Bullet", "John", "20th"
end
describe "#{new}" do
it "returns new object of Movie" do
@movie.should be_an_instance_of Movie
end
it "throws ArgumentError when give less than 3 parameters" do
lambda {Movie.new(:director => "John", :studio => "20th")}.should raise_exception ArgumentError
end
end
describe "#title" do
it "returns the correct title" do
@movie.title.should eql "Bullet"
end
end
describe "#director" do
it "returns the correct director" do
@movie.director.should eql "John"
end
end
describe "#studio" do
it "returns the correct studio" do
@movie.studio.should eql "20th"
end
end
end
Run Code Online (Sandbox Code Playgroud)
没有那个构造函数,所有测试都失败了......
ActiveModel提供的默认构造函数非常好.如果删除了你编写的构造函数,你应该能够使用如下的默认构造函数:
@movie = Movie.new(title: 'The Hobbit', director: 'Peter Jackson', studio: 'New Line Cinema')
Run Code Online (Sandbox Code Playgroud)
当你不想提供三个参数时(比如你的new行动),你可以坚持下去@movie = Movie.new
| 归档时间: |
|
| 查看次数: |
12935 次 |
| 最近记录: |