• 0

[Ruby on Rails] ActiveRecord Forms Question


Question

I have a survey and I have survey_memberships. I have a field under survey_memberships which says whether they have completed the survey or not. By default it is 0. I want to set this to 1 using a form. I used to be setting completed under the surveys table which is why that is how it looks in my form below.

The form is under the survey controller. But the field I want to set now is under my survey_memberships form.

Here is what the form looks like.

<% form_for(:survey, :url => survey_path(@survey), :html => { :multipart => true, :method => :put }) do |f| %>
		  <p>
		    <%= hidden_field_tag 'survey[completed]', '1' %>
		  </p>
		  <p>
		    <%= submit_tag 'I am finished taking this survey'.l %> 	or <%= link_to 'Cancel and go back to all surveys'.l, surveys_path %>
		  </p>
		<% end %>

I am pretty stupid in Rails. I can try to provide more details if you need them. Any help would be greatly appreciated.

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

In active record X_Ys would be a join table for members of Y that belong to X.

For example:

class Person < AR:B
  has_and_belongs_to_many :jobs
end

class Jobs < AR:B
  has_and_belongs_to_many :jobs
end

You'd expect a people table with things like name, age, address. You'd have a jobs table with info like company name, title, role, etc.

They'd be connected by a table called people_jobs with two foriegn keys: person_id and job_id. Any one person could have multiple jobs

and any single job could be filled by more than one person.

Given the nature of what you're trying to do, this doesn't seem like the right way to go about what you want. What you want is something like:

class Membership < AR:B
  has_one :survey
end
class Survey < AR:B
  belongs_to :membership
[code]

Your survey will have a "membership_id" key which is used to it 1:1 with a person.  When you create a survey from your form:
[code]
# somewhere in your survey controller

@survey = Survey.new(params[:survey])
membership = Membership.find(10) # do a proper look-up here
@survy.membership = membership

# more code here

You can switch the order of the has_one/belongs to depending on what the dominant object is.

From this you can tell if a survey has been completed by checking a survey's person property: if it's set then it's completed,

if it's not set then it hasn't been completed.

This is not the sort of thing that should be done in your view: there may be some case where it belongs in the controller but

there's a very good probability (90%+) that the correct place for this logic is in the model.

Without a much better description of the problem it's going to be nearly impossible to offer good advice.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.