I am working on a app for my kids to log their chores. I have 3 children (Nick, Siena, Mac) and have a home page with each name hyperlinked ...
I have the following associations:
Child:
has_many :completions
has_many :chores, :through=>:completion
Completion:
belongs_to :child
belongs_to :chore
Chore:
has_many :completions
has_many :kid, :through=>:completion
How do I (upon clicking the child's name) save the child_id as a session object for posting completions to the completions models?
How do I clear / change that sesison to a new child when another child clicks their name in the homepage?
Any help is greatly appreciated. Thanks, CB
So josh went above and beyond. As a noob i was asking something much more simple and elementary for most folks. The answer was quite simple:
ApplicationController
private
def current_child
child = Child.find(params[:id])
session[:child_id] = child.id
end
end
This allowed me to store that child's id in a session and post to the completed model.
If I understand the question correctly (at least as described in your comment), I did something similar recently. See Building a nested attribute from multiple parent objects. Basically, I used polymorphic_url to make a link to create a new item (I would probably use #child.chores.build(params)) and pass the attribute :chore_id, i.e.
link_to "Mark as complete", polymorphic_url([:new, #child, :completion], :chore_id => #chore.id)
In your controller make sure that for your ChoresController#new you have something like
def new
#chore = <current_child>.chores.build(params)
end
Hope this helps.
Related
I'm not getting a concept (nothing new there) on how to scope a Active Record query. I want to only receive the records where there is a certain condition in a related record. The example I have happens to be polymorphic just in case that is a factor. I'm sure there is somewhere where this is explained but I have not found it for whatever reason.
My Models:
class User < ActiveRecord::Base
belongs_to :owner, polymorphic: true
end
class Member < ActiveRecord::Base
has_one :user, as: :owner
end
I want to basically run a where on the Member class for related records that have a certain owner_id/owner_type.
Lets say we have 5 Members with ids 1-5 and we have one user with the owner_id set to 3 and the owner_type set to 'Member'. I want to only receive back the one Member object with id 3. I'm trying to run this in Pundit and thus why I'm not just going at it form the User side.
Thanks for any help as always!!!
Based on your comment that you said was close I'd say you should be able to do:
Member.joins(:user).where('users.id = ?', current_user.id)
However based on how I'm reading your question I would say you want to do:
Member.joins(:user).where('users.owner_id = ?', current_user.id)
Assuming current_user.id is 3.
There may be a cleaner way to do this, but that's the syntax I usually use. If these aren't right, try being a little more clear in your question and we can go from there! :)
In my Rails app Users can have many People which in turn can (but don't have to) belong to Organisations.
In short, this:
Users --< People >-- Organisations
Now, it would be nice to be able to create new organisations from within a people view somehow. It tried this:
class Person < ActiveRecord::Base
attr_accessible :name, :organisation_attributes
belongs_to :user
belongs_to :organisation
accepts_nested_attributes_for :organisation
end
But it's not working because Organisation is not a child of Person.
Is there another way to realise this?
Thanks for any help.
I can see that Person is actually a child of Organisation and its possible to make nested form for parent model also. And you are already using accepts_nested_attributes_for.
Im assuming that you want to show a Organisation form for a already saved person. Then
In your PeopleController#show method build the organisation
#person.build_organisation
And in people/show.html.erb
form_for(#person) do |f|
f.fields_for(:organisation) do |fo|
# show the fields of organisation here.
end
end
It should work.
Update:
I tried something similar and it worked :) Ive made a gist including the snippets.
Please follow the link https://gist.github.com/3841507 to see it working.
I'm very new to web-development (I feel like all my posts lately have started that way) and becoming, with time, less new to rails. I'm at a point where I can do a sizeable amount of the things required for my job but there's one nagging problem I keep running into:
How do I decide if which action I should use for a given task? index, show, new, edit, create, update or destroy?
destroy is pretty obvious and I can loosely divide the rest into two buckets with index/show in one and new/edit/create in the other. But how do I decide which one to use or if I should build one of my own?
Some general guidelines or links to further reading would be very beneficial for me.
Here is how I think of these 7 RESTful Controller actions. Take, for example, a Person resource. The corresponding PeopleController would contain the following actions:
index: List a set of people (maybe with some optional conditions).
show: Load a single, previously created Person with the intention of viewing. The corresponding View is usually "read-only."
new: Setup or build an new instance of a Person. It hasn't been saved yet, just setup. The corresponding View is usually some type of form where the user can enter attribute values for this new Person. When this form is submitted, Rails sends it to the "create" action.
create: Save the Person that was setup using the "new" action.
edit: Retrieve a previously created Person with the intention of changing its attributes. The changes have not been made or submitted yet. The corresponding View is usually a form that Rails will submit to the "update" action.
update: Save the changes made when editing a previously created Person.
destroy: Well, as you guessed, destroy or delete a previously created Person.
Of course there is some debate as to whether these 7 actions are sufficient for all controllers, but in my experience they tend to do the job with few exceptions. Adding other actions is usually a sign of needing an additional type of resource.
For example, say you have an HR application full of Person resources you are just dying to hire. In order to accomplish this, you may be tempted to create a "hire" action (i.e., /people/456/hire). However, a more RESTful approach would instead consider this the "creation" of an Employment resource. Something like the following:
class Person < ActiveRecord::Base
has_many :employments
has_many :employers, :class_name => 'Company', :through => :employments, :source => :company
end
class Employement < ActiveRecord::Base
belongs_to :person
belongs_to :company
end
class Company < ActiveRecord::Base
has_many :employments
has_many :employees, :class_name => 'Person', :through => :employments, :source => :person
end
The EmploymentsController's create action would then be used.
Okay, this is getting long. Don't be afraid to setup a lot of different resources (and you probably won't use all 7 Controller actions for each of these). It pays off in the long run and helps you stick to these 7 basic RESTful actions.
You can name your actions whatever you want. Generally, by Rails convention, index is the default one, show shows one item, list shows many, new and edit start editing a new or old item, and create and update will save them, respectively. destroy will kill an item, as you guessed. But all these are just conventions: you can name your action yellowtail if that's what you want to do.
Alright, I'm going to try to explain this as best as possible:
I have two models
employer.rb
class Employer < ActiveRecord::Base
has_many :listings
end
listing.rb
class Listing < ActiveRecord::Base
belongs_to :employer
end
Employers login through the employers_controller and listings are created through listings_controller
I'm having trouble getting the id from the employer table being inserted into the employer_id column in each individual created listing. I hope this makes sense. If anyone has any advice, it would be much appreciated. I have a feeling this is because I'm doing this outside of the employer_controller, but not sure.
Thanks!
1) If you are not dealing as nested resource then
When you render the new action of Listing controller, you know for which employer (#employer) you want to create the listing.
So render a hidden field for employer_id using a hidden_field or hidden_field_tag
hidden_field_tag 'employer_id', #employer.id()
2) If you are dealing as nested resource and your route looks something like
/employers/:employer_id/listings/new / (Get) && /employers/:employer_id/listings
Then in create action
#employer = Employer.find(params[:employer_id])
#employer.Listing.new(params[:listing]
I think you have the employer id in your session, since they need to login to create the listing. I won't use the param from the view, then its easy for one employer to create a listing as if it was created by another employer, just by changing the id value in your hidden field. Here's what is possibly a better approach:
#employer = Employer.find(current_user.id)
#employer.Listing.new(params[:listing]
I've got a nice 3-level nested-form using formtastic_cocoon (jquery), and now I want to be able to sort the 2nd set of items in the form.
I've got jQuery ui working no problem, so now to set and update the sort order in rails.
I started following the rails bits of railscasts sortable lists
http://asciicasts.com/episodes/147-sortable-lists
The form structure is User->Tasks->Location.
In my Task Model I set index to
def index
#task = Task.find(params[:id],:order=>'position')
end
def edit
#task = Task.find(params[:id],:order=>'position')
end
and I was expecting my console to see
... FROM 'tasks' WHERE ('users'.'id' = 12) ORDER BY ('position')
or something along those lines, but there is no order by output.
Is there somewhere else that I need to define this order?? Where does the nested_object get its relationship from? The model only?
My models are
class User < ActiveRecord::Base
has_many :tasks
end
class Task < ActiveRecord::Base
belongs_to :user
end
I changed the model to
class User < ActiveRecord::Base
has_many :tasks, :order=>'position'
end
You are using the wrong model, that id is of a user, so you have to do:
User.find(params[:id]).tasks(:order => 'position ASC')
Otherwise you are just getting the task with id = 12 and not the tasks whose user_id = 12
From the answer that you've given, I suspect the real issue lies not in the tasks controller. The default order you gave is great, but if you had some other order or filter requirements, the tasks model won't quite do it either.
I suspect you were actually in users#edit, or possibly a _form.html.erb, where it displays the form elements for each task. There might have been a #user.tasks.each {...} or similar loop block.
For a given user then, do: #user.tasks.order(:position). Or maybe you need open tasks: #user.tasks.where(:open=>true) etc.
Your code is slightly wrong here.
To find that user's tasks you would do this in your route:
User.find(params[:id]).tasks(:order=>'position')