我想知道这是为什么不为我工作:Ruby on Rails的:“find_create_by_user”
Recipe.find_or_create_by_user_id(current_user.id, :name => "My first recipe")
创建该配方罚款,如果不通过用户的ID存在,但名称(“我的第一个配方“)不包含在新创建的条目中。有什么我做错了吗?我无法完全理解这一点。
我想知道这是为什么不为我工作:Ruby on Rails的:“find_create_by_user”
Recipe.find_or_create_by_user_id(current_user.id, :name => "My first recipe")
创建该配方罚款,如果不通过用户的ID存在,但名称(“我的第一个配方“)不包含在新创建的条目中。有什么我做错了吗?我无法完全理解这一点。
你可以试试这个一对夫妇不同的方式:
Recipe.find_or_create_by_user_id_and_name(current_user.id, "My first recipe")
Recipe.find_or_create_by_user_id(:user_id => current_user.id, :name => "My first recipe")
试试这样说:
Recipe.find_or_create_by_user_id(current_user.id) do |recipe|
recipe.name = 'My first recipe'
end
块将只被调用,如果它有创造纪录。
谢谢Tadman。我不知道。非常感谢! – Drew 2009-10-06 20:42:23
您有没有机会在食谱模型中使用attr_accessible或attr_protected?如果名称不可访问,那么当您通过批量分配将其传入时,它不会按预期分配。
我相信这可以解释为什么tadman的方法有效,而你的原始尝试没有。如果名称不是你有严重的安全问题,你可以考虑通过attr_accessible公开它。
谢谢,迈克尔。如果用户决定在未来改变食谱的名称会怎样? – Drew 2009-10-06 20:41:31