【发布时间】:2017-11-20 20:41:20
【问题描述】:
在向 Ruby 内置的 RESTFUL API 发出发布请求后,从 user_id、created_at 和 updated_at 表中获取一些空值。白名单参数中的大多数值都已发送,但由于某些空值未发送而“回滚”(我的假设)。
(https://s7.postimg.org/9m5v1m2u3/Screen_Shot_2017-11-20_at_12.01.58_PM.png) ![显示空值]
(https://s7.postimg.org/h5yy3ngl7/Rollback.png) ![终端显示回滚错误]
这里是 API 控制器:
class Api::V1::GigsController < ApplicationController
before_action :authenticate_user!, except: [:index, :show]
skip_before_action :verify_authenticity_token
def index
@gig_items = Gig.all
render json: @gig_items
end
def create
@gig_item = Gig.create(gig_params)
render json: @gig_item
end
def show
@gig_item = Gig.find(params[:id])
render json: @gig_item
end
private
def gig_params
params.require(:gig).permit(:title, :category, :description, :price, :main_image, :thumb_image, :status, category_ids: [])
end
end
这是使用 action creator 和 axios 的 post 请求调用
const ROOT_URL= "http://localhost:5000/api/v1/gigs"
export function createGig(values){
const request = axios.post(`${ROOT_URL}`, values);
return {
type: CREATE_GIG,
payload: request
}
}
并使用 redux-form 处理 post 请求动作以发送和验证参数:
onSubmit(values){
this.props.createGig(values);
}
render(){
const { handleSubmit } = this.props;
return(
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<Field
label="Title of Gig"
name="title"
component={this.renderField}
/>
<Field
label="Categories"
name="categories"
component={this.renderField}
/>
<Field
label="Description"
name="description"
component={this.renderField}
/>
<Field
label="Price"
name="price"
component={this.renderIntegerField}
/>
<Field
label="Status"
name="status"
component={this.renderIntegerField}
/>
<Field
label="Main Image"
name="main_image"
component={this.renderField}
/>
<Field
label="Thumb Image"
name="thumb_image"
component={this.renderField}
/>
<button type="submit" className="btn btn-success">Submit</button>
{" "}
<Link to={'/gigs'}><button type="submit" className="btn btn-danger">Cancel</button></Link>
</form>
)
}
}
export default reduxForm({
validate,
form: 'GigsNewForm'
})(
关于为什么在我的应用程序上执行 POST 请求时它会为 created_at、updated_at 和 user_id 产生空值,而其他的似乎没问题的任何想法。
【问题讨论】:
-
也许您的验证没有通过?试试
@gig_item = Gig.create!(gig_params)看看是否出现验证错误。 -
我已经找到了解决问题的方法。意识到我已经使用设计进行用户身份验证,我将 current_user 添加到 create 操作中,并且能够成功传递产生 null 的参数。感谢您的帮助。
标签: ruby-on-rails rest post react-redux httprequest