嵌套属性使用不同的主键更新

时间:2013-03-21 11:11:15

标签: ruby-on-rails ruby activerecord

我有2个模型,当我更新它时我遇到错误。我使用了嵌套属性。

 class Channel < ActiveRecord::Base
    self.primary_key = 'id'

    has_many :channel_mappings , primary_key: 'channel_name', foreign_key: 'channel_name'

    attr_accessible :channel_name, :channel_mappings_attributes

    validates_presence_of :channel_name

    accepts_nested_attributes_for :channel_mappings, :allow_destroy => true
end

第二模特

class ChannelMapping < ActiveRecord::Base
  self.primary_key = 'src_channel'

  belongs_to :channel, primary_key: 'channel_name', foreign_key: 'channel_name'

  attr_accessible :src_channel, :channel_name , :src_file_type 
end

更新方法

def update
        @channel = Channel.find(params[:id])

        if @channel.update_attributes(params[:channel])
            redirect_to @channel, notice: 'Channel was successfully updated.'
        else
            render action: 'edit'
        end
    end

错误

  Type: ActiveRecord::RecordNotFound
      Message:  Couldn't find ChannelMapping with ID=ANY NAME for Channel with ID=2

我知道&#39;与主键被覆盖有关的事情。任何帮助都会有用

分贝/ schema.rb

create_table "channels", :force => true do |t|
    t.text    "channel_name",                                  :null => false
    t.string  "internal_flag",                  :limit => nil
    t.string  "exception_flag",                 :limit => nil
  end

create_table "channel_mappings", :id => false, :force => true do |t|
    t.text    "src_channel",   :null => false
    t.text    "channel_name",  :null => false
  end

2 个答案:

答案 0 :(得分:0)

您可以尝试 - @channel.attributes = params[:channel]代替@channel.update_attributes(params[:channel])

这也将设置所有属性但不保存。

然后你可以打电话 -

@channel.save

这将保存您的属性。

错误似乎是找不到记录而不是更新恢复如。

首先检查错误日志,如果需要,请在此处发布,如果没有效果。

最好将if else条件用作:

if @channel.save
#record saved
else
#error in save
end

然后你就可以知道它的去向。

答案 1 :(得分:0)

好吧,在Channel.rb的第一行,你将主键设置为'id'。那么为什么要在关联中指定primary_key ='channel_name'?这似乎不对。

另外,在db / schema.rb中查看channel表的定义会很有帮助。

附加信息后更新

在你的要点中,我看到你的参数在channel_mappings_attributes中包含一个id键。但是,schema.rb显示channel_mappings没有id。这是你需要解决的第一件事。

相关问题