attr_accessor不适用于未保存的关联对象

时间:2017-05-23 18:26:58

标签: ruby-on-rails ruby-on-rails-5

我还没有找到解释为什么attr_accessor在这里工作:

fb_profile = FbProfile.where(identifier: params[:identifier]).first_or_initialize
fb_profile.signed_request = "randomstring"
logger.info(fb_profile.signed_request) # outputs "randomstring"

但不在这里:

current_admin.fb_profile = FbProfile.where(identifier: params[:identifier]).first_or_initialize
current_admin.fb_profile.signed_request = "randomstring"
logger.info(current_admin.fb_profile.signed_request) # outputs undefined

我可以像第一个例子一样工作,但后来我必须创建关联,这似乎比从get go创建它更脏。这是常见的行为吗?

UPDATE1:

正如一些人所要求的,以下是两种模型的相关部分:

class Admin < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :omniauthable include DeviseTokenAuth::Concerns::User has_one :fb_profile end

class FbProfile < ApplicationRecord belongs_to :admin has_and_belongs_to_many :fb_pages attr_accessor :signed_request end

1 个答案:

答案 0 :(得分:0)

您错过了current_admin和fbprofile之间的关系。

如果你有一个has_one关系,我会写这样的东西:

// DataTable with original data
// May contain DataTime with zero time.
var dt = new DataTable();

// DataTable with Date converted to string.
var dt2 = new DataTable();

var dateIndexes = new HashSet<int>();

// Create columns in dt2, changing DateTime with zero time to string type
foreach (DataColumn column in dt.Columns)
{
    if (column.DataType == typeof(DateTime) &&
        dt.Rows.Cast<DataRow>()
            .Select(row => (DateTime)row[column])
            .All(dateTime => dateTime.TimeOfDay.Ticks == 0))
    {
        // If all time is zero then create string type column.
        dt2.Columns.Add(column.ColumnName, typeof(string));
        // Remember the index of the column with zero time
        dateIndexes.Add(column.Ordinal);
    }
    else
    {
        // Create column same type.
        dt2.Columns.Add(column.ColumnName, column.DataType);
    }
}

// Copy rows
foreach (DataRow row in dt.Rows)
{
    var newRow = dt2.NewRow();
    dt2.Rows.Add(newRow);

    for (int i = 0; i < row.ItemArray.Length; i++)
    {
        if (dateIndexes.Contains(i))
        {
            // Column with zero time. Convert it to string.
            newRow[i] = ((DateTime)row[i]).ToShortDateString();
        }
        else
        {
            // Copy as is.
            newRow[i] = row[i];
        }
    }                    
}