2011-10-03 42 views
0

在我的Rails 3應用程序中,每個用戶的配置文件都有一個我想要添加的數組。這些項目是唯一的,但會添加到兩個類別中的一箇中的每個配置文件。然而,我遇到的問題是將profile_item通過它們的ID鏈接到該項目。Rails 3數組問題

profile.rb型號:

class Profile < ActiveRecord::Base 
    belongs_to :user 
    accepts_nested_attributes_for :user 

    has_many :profile_todos 
    has_many :todos, :through => :profile_todos 

    def add_todo_inside_item(item) 
    self.profile_todos.build :category => 'inside' 
    end 

    def add_todo_outside_item(item) 
    self.profile_todos.build :category => 'outside' 
    end 
end 

todo.rb型號:

class Todo < ActiveRecord::Base 
    belongs_to :profile 
end 

profile_todo.rb型號:

class ProfileTodo < ActiveRecord::Base 
    belongs_to :profile 
    belongs_to :todo 
end 

Todo.new給出如下:

>> Todo.new 
=> #<Todo id: nil, name: nil, created_at: nil, updated_at: nil> 

ProfileTodo.new給出如下:

>> ProfileTodo.new 
=> #<ProfileTodo id: nil, category: nil, profile_id: nil, created_at: nil, updated_at: nil> 

我使用調用我的配置文件profile_todos

<div id="todosheader"> 
    <p><%= @profile.first_name %>&nbsp;has&nbsp;<%= pluralize(@profile.profile_todos.count, 'todo') %>.</p> 
</div> 
<div id="todo-list"> 
    <div class="todos_inside"> 
    <h4>Inside&nbsp;(<%= @profile.profile_todos(:category => "inside").count %>)</h4> 
    <p><%= @profile.profile_todos(:category => "outside") %></p> 
    </div> 
    <div class="todos_outside"> 
    <h4>Outside&nbsp;(<%= @profile.profile_todos(:category => "outside").count %>)</h4> 
    <p><%= @profile.profile_todos(:category => "outside") %></p> 
    </div> 
</div> 

如何能夠我將todo添加到配置文件中,其中將Todo:name與給定:category一起添加到配置文件?現在呼叫@profile.profile_todos返回一個空數組。

假設我有一個Todo的「測試」,ID爲「1」。如果我嘗試使用@profile.add_todo_inside_item("Test")Todo添加到我的profile_todos陣列中,我似乎無法將「測試」Todo附加到我的profile_todos(:category => "inside")

+0

從你的例子還不清楚要如何來調用這個。鑑於上面的代碼,調用Todo.new或ProfileGoal.new並期望除了空實例以外的任何其他內容都沒有任何意義。 – Tilo

+0

我想要做的就是'todos'可供所有用戶添加到他們的'profile_todos'中。但我想按類別將「todos」添加到「profile_todos」,無論是「inside」還是「outside」。所以我想要取一個'todo'的名字(字符串值),給它一個類別,並將它添加到'profile_todos'中。這樣我可以將profile_todos分隔成'profile_todos(:category =>「inside」)''''profile_todos(:category =>「outside」)''。希望這是有道理的。 – tvalent2

回答

0

我不知道你想在這裏做什麼..

待辦事項應該是複數..你應該保存父..

class Profile < ActiveRecord::Base 
    has_many :todos 

    def new_inside_todo(params) # takes a hash of all attributes, like new() 
     params.merge!({:category => "inside"}) 
     self.todos.build(params) 
     self.save(:validate => false) 
    end 

    def new_outside_todo(params) 
     params.merge!({:category => "outside"}) 
     self.todos.build(params) 
     self.save(:validate => false) 
    end 
end 

class Todo < ActiveRecord::Base 
    belongs_to :profile 

    # has an attribute called category 

    # if Todos belong to more than one class, make the relationship polymorphic 
    #  belongs_to :parent , :polymorphic => true 
end 
+0

我剛剛爲我的問題添加了更新。我希望能提供更多的見解。謝謝您的幫助! – tvalent2