I am developing an "issue tracker" app in Rails 3 but I am having trouble describing the relationship between an "Issue" and its "Status". Each issue can only have one status - I'd like this to be a combo box in HTML - but clearly each status can be assigned to multiple issues. I started with "issue has one status" but then I ran into problems retrieving that status in the view. I assume this is correct, but I must need something else...
3 回答
In this case an issue belongs to a certain status:
class Issue
belongs_to :status
end
Think of status as a type of category that each issue belongs to.
If you won't be allowing a custom status, it makes more sense to have the all status' as a constant array (used for select) and a status
string field in issues. You will still be able to list all issues with a status with a scope.
Update for the question
class Issue
STATUSES = [ "Open", "Closed" ]
scope :with_status, lambda { |status| where(:status => [*status]) }
end
In view,
<%= f.select :status, Issue::STATUSES %>
You'll need a field in the database. So in a migration:
add_column :issues, :status, :string
To find Issues with status in controller:
@open_issues = Issue.with_status("Open").all;
@current_issues = Issue.with_status([ "Pending", "Waiting on Review"]).all;
Or with an association:
@closed_issues = @project.issues.with_status("Closed");
You should be using Issue belongs_to :status
and Status has_many :issues
instead.
When you use a has_one
association, Rails will look for the foreign key issue_id
in the statuses
table. This is not what you want. You want issues to point to statuses, not vice versa.