2013-07-18 38 views
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_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。

我不知道为什么这是发生在索引方法,但不是创建方法。谢谢!

+0

为什么你有两个'user'和'user_id'?如果'UserVacationDay belongs_to:user',我非常确定rails会被'user'和'user_id'属性混淆。通常,如果您执行'@user_vacation_day.user = current_user',则会将'user_id'设置为'current_user'的'user_id'。 – theIV

+0

我认为你是对的,我想只有user_id。问题是,我不知道如何从user_id获取用户对象。 Rails控制台简单地返回用户ID号 – Mike

+0

如果从模型中删除'user'属性并设置一个'belongs_to'关联(就像我上面提到的那样),执行'@ user_vacation_day.user'将返回'User'对象,而不仅仅是id。 – theIV

回答

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 
+0

您正在使用.new而不是.create。这是正确的吗?我很抱歉,我对rails很新,我认为create是实际构建对象并将其添加到数据库的方法 – Mike

+0

'new'创建对象,但尚未将其保存到数据库。然后,您可以设置'user'参数并使用'@ user_vacation_day.save'保存它。这使得动作只向数据库发送一条INSERT语句,并且通常如何在Rails中实现'create'动作。 – henrikhodne

相关问题