Allow Active Record Model to Assign Association us

2019-09-16 05:30发布

I have a fairly basic set of models where a 'Project' has one 'Owner'. I'd like to allow users to enter the owner's name when creating a new project. If owner doesn't exist, a new one should be created. Does a good way to do this exist? I've been thinking about using attr_accessor and before_validation however it seems it would conflict with the relationship. Any ideas? Thanks!

2条回答
仙女界的扛把子
2楼-- · 2019-09-16 06:08

I'd use something along the lines of this in your controller:

def update
  Project.transaction do
    @project.owner = Owner.find_or_create_by_name(params[:project].delete(:owner_name))
    @project.attributes = params[:project]
    @project.save!
  end
end
查看更多
叼着烟拽天下
3楼-- · 2019-09-16 06:14

Use something different than the name of your relationship... owner_name should be fine. Then write the necessary before_validation method.

查看更多
登录 后发表回答