Issue with Rails 3 array
In my Rails 3 app, every User's profile has an array that I want to add to. The items are unique, but are added to each Profile in one 开发者_运维技巧of two categories. What I'm having trouble with however is linking the profile_item to the item through their IDs.
profile.rb Model:
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 Model:
class Todo < ActiveRecord::Base
belongs_to :profile
end
profile_todo.rb Model:
class ProfileTodo < ActiveRecord::Base
belongs_to :profile
belongs_to :todo
end
Todo.new
gives the following:
>> Todo.new
=> #<Todo id: nil, name: nil, created_at: nil, updated_at: nil>
ProfileTodo.new
gives the following:
>> ProfileTodo.new
=> #<ProfileTodo id: nil, category: nil, profile_id: nil, created_at: nil, updated_at: nil>
I'm calling the profile_todos
in my profiles using:
<div id="todosheader">
<p><%= @profile.first_name %> has <%= pluralize(@profile.profile_todos.count, 'todo') %>.</p>
</div>
<div id="todo-list">
<div class="todos_inside">
<h4>Inside (<%= @profile.profile_todos(:category => "inside").count %>)</h4>
<p><%= @profile.profile_todos(:category => "outside") %></p>
</div>
<div class="todos_outside">
<h4>Outside (<%= @profile.profile_todos(:category => "outside").count %>)</h4>
<p><%= @profile.profile_todos(:category => "outside") %></p>
</div>
</div>
How can I add a todo
to the profile where the Todo
:name
is added with a given :category
to the Profile? Right now calling @profile.profile_todos
returns an empty array.
Let's say I have a Todo of "Test", with an ID of "1". If I try to add that Todo
to my profile_todos
array using @profile.add_todo_inside_item("Test")
, I can't seem to attach the "Test" Todo
to my profile_todos(:category => "inside")
.
I'm not sure what you want to do here..
todos should be plural.. and you should save the parent..
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
精彩评论