Reputation: 4976
UPDATE
I answered my question below, but I am still asking for a prettier way to achieve my goal. I have a feeling my controller knows too much about how to do things.
I have a create action in my VideoController :
def create
method = 'get_' + params[:video][:provider] + '_video_id'
provider_video_id = Video.send(method, params[:video][:url])
thumb = Video.get_thumb_from_youtube(provider_video_id)
@video = Video.new(params[:video], :provider_video_id => provider_video_id, :thumb => thumb, :views => 0, :likes => 0)
if @video.save!
redirect_to video_path('1'), notice:'Video added successfully.'
else
render :new
end
end
I call Video.new with params[:video]
with get its information from a form the user fills in. I then manipulate the URL the user passed in with the form to recover the video_provider_id
and thethumb
.
However, Rails is not saving the video with provider_video_id
and thumb
... I get this error on save :
Validation failed: Thumb can't be blank, Thumb is invalid, Provider video can't be blank
My guess is the new
method doesn't accept extra parameters...
Upvotes: 1
Views: 1698
Reputation: 16629
But if you want, you can always override the default new action with something like
class Video
def new(attr1, attr2)
super
#do something with attr2
end
end
Upvotes: 1
Reputation: 1447
You may want to use .merge()
:
Instead of
method = 'get_' + params[:video][:provider] + '_video_id'
params[:video][:provider_video_id] = Video.send(method, params[:video][:url])
params[:video][:thumb] = Video.get_thumb_from_youtube(params[:video][:provider_video_id])
params[:video][:views] = params[:video][:likes] = 0
@video = Video.new(params[:video])
You can do (modifying code from the original question):
@video = Video.new(params[:video].merge(:provider_video_id => provider_video_id, :thumb => thumb, :views => 0, :likes => 0))
That will merge the params into one hash.
Upvotes: 1
Reputation: 63
How about a before save callback in your model? This is an off-the-top-of-my-head default value example, but you could pass params in too.
after_initialize :url
private
def url
self.provider_video_id ||= "default value"
end
Upvotes: 1
Reputation: 4976
I solved the problem. I think Ruby on Rails' new
method doesn't accept more than one parameter, which usually is params
. What I did is I the following :
method = 'get_' + params[:video][:provider] + '_video_id'
params[:video][:provider_video_id] = Video.send(method, params[:video][:url])
params[:video][:thumb] = Video.get_thumb_from_youtube(params[:video][:provider_video_id])
params[:video][:views] = params[:video][:likes] = 0
@video = Video.new(params[:video])
Now, it seems to work.
Upvotes: 0