问题
I have two models: Schedule and Project. Schedule belongs_To Project and Project has_one schedule. There are several problems, but i think they all have the same cause. Here is the code for the schedules#create controller:
def create
@schedule = Schedule.new(schedule_params)
@schedule.project = Project.find(params[:project_id])
if @schedule.project.student_id == current_user.id
if @schedule.save && @schedule.freelancer_accepts
flash[:notice] = "Successfully created schedule."
redirect_to profile_path(current_user.profile_name)
else
render :action => 'new', :notice => 'Invalid Schedule'
end
else
render :action => 'new', :notice => 'Schedule is invalid.'
end
end
Here are the problems:
Even though it is a has_one relationship, I am still able to create many schedules for a single project. This led me to change my controller to this:
def create if !Schedule.where(project_id: params[:project_id]).any? @schedule = Schedule.new(schedule_params) @schedule.project = Project.find(params[:project_id]) if @schedule.project.student_id == current_user.id if @schedule.save && @schedule.freelancer_accepts flash[:notice] = "Successfully created schedule." redirect_to profile_path(current_user.profile_name) else render :action => 'new', :notice => 'Invalid Schedule' end else render :action => 'new', :notice => 'Schedule is invalid.' end else render :action => 'new', :notice => 'A schedule has already been created.' end end
The change was that I essentially wrapped the controller in an if that says "if a schedule exists, don't create one. After I changed my code, I got the following problems:
In firefox, when I press the submit button to create a new schedule, i get this error:
First argument in form cannot contain nil or be empty
In Safari, when I press the submit button to create a new schedule, the page turns white. Furthermore, every time I try to go back to the page which displays the form, the page goes white. It is very strange.
How do I fix this? Thanks.
UPDATE: My routes and form view might help:
routes:
resources :projects do
resources :schedules
end
First part of form:
<%= form_for [@project, @schedule] do |f| %>
回答1:
Turns out this and several other problems i was having was not actually caused by the has_one relationship. There was some type of problem with my cache. I'm not exactly sure what it was, but by disabling the cache I was able to fix the problem.
来源:https://stackoverflow.com/questions/20151104/rails-has-one-relationship-causing-problems-also-white-screen