Rails:表单不会向模型添加数据

时间:2014-10-16 17:59:50

标签: ruby-on-rails ruby forms ruby-on-rails-4 textbox

我有一个用于创建new:thing的表单,使用collection_select字段输入现有的:new:thing与之相关的东西。每个:东西has_many:东西,通过中间模型:related_things,它有一个thing_a_id和thing_b_id。因此,当我填写该字段并单击提交时,应该创建一个:related_thing,其中thing_a_id和thing_b_id分别等于两个thing_ids。但不是这样的:related_thing被创建;表格没有做任何事情。其他文本域确实有用。我的代码出了什么问题?

我使用的是Rails 4.0.10。

事物/新观点:

<h1>Add Something!</h1>
<p>
  <%= form_for @thing, :url => things_path, :html => { :multipart => true } do |f| %>

    <%= f.text_field :name, :placeholder => "Name of the thing" %>
    <br>
    <%= f.label :related_things %>
    <%= f.collection_select :related_things, Thing.all, :id, :name %>
    <br>
    <%= f.label :display_picture %>
    <%= f.file_field :avatar %>
    <br>
    <%= f.submit "Submit", class: "btn btn-primary" %>
  <% end %>
</p>

事物模型:

class Thing < ActiveRecord::Base
  has_many :related_things
  has_many :things, :through => :related_things
  has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "30x30!" }, :default_url => "/images/:style/missing.png"
  validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/

  def related_things
    related_thing_ids = RelatedThing.
        where("thing_a_id = ? OR thing_b_id = ?", self.id, self.id).
        map { |r| [r.thing_a_id, r.thing_b_id] }.
        flatten - [self.id]
    Thing.where(id: related_thing_ids)
  end

  def related_thing_ids=(ids)
    ids.each do |id|
      record = RelatedThing.where(thing_a_id: self.id, thing_b_id: id).first
      record ||= RelatedThing.where(thing_a_id: id, thing_b_id: self.id).first
      record ||= RelatedThing.create!(thing_a_id: self.id, thing_b_id: id)
    end
  end

end

RelatedThing模型:

class RelatedThing < ActiveRecord::Base
  has_many :things
end
事物控制器:

class ThingsController < ApplicationController

  def show
    @thing = Thing.find(params[:id])
    @related_thing = RelatedThing.all
    @thing.things.build  
  end

  def new
    @thing = Thing.new
    @things = Thing.all
  end

  def create
    @thing = Thing.new(thing_params)
    if @thing.save
      redirect_to @thing
    else
      render 'new'
    end
  end

  private

    def thing_params
      params.require(:thing).permit(:name, :image_path, :avatar)
    end

end

RelatedThings Controller:

class RelatedThingsController < ApplicationController
  def new
    @things = Thing.all.by_name
  end

  def create
    @things = Thing.all.by_name
  end

  def edit
    @things = Thing.all.by_name
  end
end

2 个答案:

答案 0 :(得分:1)

我相信,集合选择应该命名为related_thing_ids,以使您的模型正常工作。

答案 1 :(得分:1)

造成这种情况有两个问题:

  1. 正如Jamesuriah指出的那样,您的collection_select应该使用related_things_ids字段。

  2. 尽管有这样的改变,由于Rails'Strong Parameters,该字段实际上已从参数图中过滤掉。

  3. 具体来说,在您的控制器中,thing_params方法应如下所示:

    def thing_params
      params.require(:thing).permit(:name, :image_path, :avatar, :related_things_ids)
    end
    

    阅读上面链接中的强参数以获取更多信息。希望有所帮助!