0

我有一个对象在我的 rails 应用程序中表现得很奇怪。

我的 2 个控制器方法是相关的。

  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 是如何为零的。不应该,我也不明白为什么。让我抓狂的是我的索引表。它显示所有休假日请求。以下部分实际上在浏览器中工作,并且提交和所有内容都没有明显的错误。这里是:

- @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 方法中却没有。谢谢!

4

1 回答 1

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
于 2013-07-18T17:39:14.863 回答