Rails简单表单关联提交未更新

时间:2015-10-23 09:57:26

标签: ruby-on-rails forms ruby-on-rails-4 simple-form

我遇到has_many关系设置表单的问题,这些表单在提交后不会更新值。

示例

提交新字符时,vn_id没有更新,当我尝试检查Vn中的字符时,在Rails控制台中,它返回空。

我正在尝试为属于Vn的字符设置一个表单,该表单将通过关联进行链接,但在提交时,它不会链接到Vn。

class Character < ActiveRecord::Base
    validates :name, :presence => true
    validates :summary, :presence => true
    belongs_to :vn
end

class Vn < ActiveRecord::Base
  has_many :characters
  validates :name, presence: true
  accepts_nested_attributes_for :characters
end

创建新角色的表单

<%= simple_form_for @character do |f| %>
      <div class="col-lg-12">
        <%= f.input :summary,input_html: {style: "height:150px;"} %>
    </div>
      <div class="col-lg-12">
        <%= f.association :vn, as: :check_boxes %>
    </div>
      <%= f.button :submit , class: "btn btn-primary" %>
    <% end %>

控制器

class CharactersController < ApplicationController

    def show
        @character = Character.find(params[:id])
    end

    def new
        @character = Character.new
    end

    def create  
        @character = Character.new(char_params)  
        if @character.save

        else
            render :action=>"new"
        end

    end

    private
        def char_params
        params.require(:character).permit(:name, :summary,:voiceactor,:vn_name,vn_id: [])
    end

end

class VnsController < ApplicationController

    def show
        @vn = Vn.find(params[:id])
    end

    def new
        @vn = Vn.new
    end

    def create  
        @vn = Vn.new(vn_params)  
        if @vn.save

        else
            render :action=>"new"
        end

    end

    private
        def vn_params
    def vn_params
        params.require(:vn).permit(:name, :summary,:genre,:developer,:rating,vn_id: [])
    end

    end

end

提交未经许可的vn_id

  Parameters: {"utf8"=>"✓", "authenticity_token"=>"O2s6GVs77GGUMC5u3eZ9ebv/0l5u0MwP44yS8WGCQnjgwSgHfkbCmhEOUo6WKIMSMo5IfDuNYtMzyphnT/5cwQ==", "character"=>{"name"=>"2222", "voiceactor"=>"111", "summary"=>"one two tthee", "vn_id"=>"32"}, "commit"=>"Create Character"}
Unpermitted parameter: vn_id
   (0.1ms)  begin transaction
  SQL (0.6ms)  INSERT INTO "characters" ("name", "summary", "voiceactor", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?)  [["name", "2222"], ["summary", "one two tthee"], ["voiceactor", "111"], ["created_at", "2015-10-23 10:34:00.285447"], ["updated_at", "2015-10-23 10:34:00.285447"]

2 个答案:

答案 0 :(得分:0)

不知何故,将CharactersController中的vn_id: []更改回:vn_id

答案 1 :(得分:0)

问题是你试图允许数组进行单一关联

f.association输入是针对您的belongs_to关联的,为什么它会允许多条记录?

您甚至可以查看其工作原理here

enter image description here

以上是仅针对has_many

的方法

简而言之,它们不存在belongs_to

因此,当您致电f.association :vn时,您将填充属性vn_id,然后该属性可以在您的数据库中关联。

如果您使用vn_ids等,那么您has_many的唯一时间就是

这意味着......

def character_params
    params.require(:character).permit(:vn_id) 
end

f.association :vn

......应该有效