obviously I'm quite new to rails, so stick with me.
I've added a constructor to my model
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
and that sort of messed up things for me. Befor I've had a method 'new' in my controller like this
def new
@movies = Movie.new
end
and it worked nicely before the initialize came along. It requires parameters to be passed to the 'new' method, but that was done after a view was open for passing arguments from a user and saving them. Now I can't open that view because I get an error
wrong number of arguments (0 for 3)
The constructor was added due to the fact I started writting test for my application and setting default vaules for the constructor will nullify that test. Suggestion on solving this?
EDIT: My tests look like this:
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
Without that constructor all the tests fail....
You can pass parameters using form or using ajax. Once you pass a parameters to your server (controller) you can check it to your server log to see the parameters. In rails 4 you need to use Strong Parameters to save these parameters to your database. Save this answer.
Pass-by-reference means that the arguments of a method are references to the variables that were passed into the method, and modifying the arguments modifies the original variables. If Ruby were pass-by-reference, changing the value of the argument (arg) would change the value of the variable val .
The default constructor provided by ActiveModel is pretty good. If you delete the constructor you wrote, you should be able to use the default constructor like this:
@movie = Movie.new(title: 'The Hobbit', director: 'Peter Jackson', studio: 'New Line Cinema')
When you don't want to provide the three arguments (like in your new
action), you can stick with @movie = Movie.new
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With