开发者

Rails 3- Handling a conditional Create in a Controller

I have the following in my def create controller:

@photo = current_user.photos.crea开发者_StackOverflowte(params[:photo].merge(:project_id => params[:project_id])

In my app photo records are valid if they have a project_id or not....

But I need my create statement not to error and work for both cases. A. If there is a param project_id, insertit B. If not, insert the default NULL value when creating the record

What's the smartest Rails3 way to accomplish this?

Thanks


Unless you have an ActiveRecord validation in place, the create method should not raise if a column is nil.


You could do something like:

<%= f.hidden_field :project_id, :value => PROJECT_ID_WHICH_CAN_BE_NULL_OR_NOT %>

inside your view, in the photo form. The controller would then be:

@photo = current_user.photos.create(params[:photo])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜