我的rails应用程序中有一个非常奇怪的对象。
我的两种控制器方法是相关的。
def index
@user_vacation_days = UserVacationDay.all
end
真的很简单。
def create
params[:user_vacation_day][:user_id] = current_user.id
params[:user_vacation_day][:user] = current_user # supplementary
@user_vacation_day = UserVacationDay.create(params[:user_vacation_day]) #user_vacation_day
@user_vacation_day.update_attributes(user: current_user)
if @user_vacation_day.persisted?
flash[:notice] = "Request Sent"
redirect_to dashboard_index_path
#UserVacationDayMailer.request_vacation_days(@user_vacation_day.id).deliver
else
flash[:notice] = "Something went wrong, please try again"
render :new
end
end
这个很棘手。行
params[:user_vacation_day][:user_id] = current_user.id
params[:user_vacation_day][:user] = current_user
行为不端。当我进入我的rails控制台,然后输入
UserVacationDay.all
我得到了
[#<UserVacationDay id: 34, user: nil, description: "work!", response: nil, response_description: "placeholder", created_at: "2013-07-18 15:46:07", updated_at: "2013-07-18 16:29:24", state: "denied", number_of_days_off_requested: 100, user_id: 1>]
注意用户如何为零。它不应该,我不明白为什么。让我疯狂的是我的索引形式。它显示所有休假日请求。以下细分实际上可以在浏览器中运行,并提交所有内容而不会出现明显的错误。这是:
- @user_vacation_days.each do |u|
#{u.user.full_name} has requested #{u.number_of_days_off_requested} vacation days
%br
"#{u.description}"
%br
.btn-group
%button.btn.btn-primary.dropdown-toggle
= link_to "Respond", edit_user_vacation_day_path(u)
它允许我调用u.user.full_name,这与调用@ user_vacation_day.user.full_name相同。
我不知道为什么会在index方法中发生这种情况,而不是create方法。谢谢!
答案 0 :(得分:1)
实施create
行动的更好方法可能是:
def create
@user_vacation_day = UserVacationDay.new(params[:user_vacation_day])
@user_vacation_day.user = current_user
if @user_vacation_day.save
flash[:notice] = "Request Sent"
redirect_to dashboard_index_path
else
flash[:notice] = "Something went wrong, please try again"
render :new
end
end