Rails多态关联不会保存_type

时间:2016-12-30 08:34:24

标签: ruby-on-rails polymorphic-associations

我的项目中有几个模型:请求,工作,汽车和员工。工作是Request和Car / Employee之间的中间模型。

以下是关联:

请求

belongs_to :request
belongs_to :performer, polymorphic: true

工作

has_many :works, as: :performer
has_many :requests, through: :works, as: :performer

汽车

has_many :works, as: :performer
has_many :requests, through: :works, as: :performer

员工

<%= form_for([@request, @work]) do |f| %>
    <%= (f.collection_select :performer_id, Employee.all, :id, :name) if @request.type == "StaffRequest" %>
    <%= (f.collection_select :performer_id, Car.all, :id, :select_info) if @request.type == "CarRequest" %>
    <%= f.submit 'OK' %>
<% end %>
用于创建作品的

查看

  def new
    @work = @request.works.new
  end

  def create
    @work = @request.works.new(work_params)
  end

  def work_params
      params.require(:work).permit(:performer_id, :request_id)
  end

工作控制器

php /magento-path/www/shell/compiler.php clear

php /magento-path/www/shell/compiler.php compile

问题是我的performer_type列始终为空,它不保存类名。可能是什么问题?有什么想法吗?

2 个答案:

答案 0 :(得分:2)

它是空的,因为你没有通过它,你应该为你的形式添加一个隐藏的字段:

SimpleDraweeView imageview = (SimpleDraweeView) findViewById(R.id.imageview);
String fileInternalPath = "....";
Uri bmpImageUri = Uri.parse(fileInternalPath);
imageview.setImageURI(bmpImageUri);

答案 1 :(得分:0)

旁边:performer_id,你还必须传递:performer_type,一种方法是通过表单select_tag:

def create 
  @work = @request.works.new(work_params)
end

def work_params
  # use :performer if you use :performer as in the select form field
  params.require(:work).permit(:performer, :request_id)

  # OR

  # use :performer_id & :performer_type if you also use the hidden field
  params.require(:work).permit(:performer_id, :performer_type, :request_id)
end

有一个很好的例子(对于Rails 4.2)使用单个选择表单字段进行多态,因此您可以这样编写:

<%= f.grouped_collection_select :global_performer, [ Car, Employee ], :all, :model_name, :to_global_id, :name %>

How to create grouped select box in Rails for polymorphic association using Global ID?