Passing an instance of one object to another

Hello,

I'm working on my first Rails app. It's a redesign for a magazine
site. I have a class for the articles and a class for issues. I've
set up a has_many/belongs_to relationship between the two so that
every article belongs to a particular issue.

Now I'd like to set it up so that a new article cannot be added UNLESS
you have already chosen the issue that it is to be added to. I'd like
to set something up like
"selected_issue.articles.build(params[:article])" but I don't know how
to create an action/method that would allow me to set the
selected_issue variable and then pass that into the create method on
the article controller.

Could someone lend some assistance here?

Thanks.

you got it right. you can call
@issue.articles.create( params[:article] ) to get a new article that
is already saved and associated with the issue. you can also do
@issue.articles.build( params[:article] ) if you want to get a new
article object but not save it yet.

see here: http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html#M000642

A common way to do this is for your "create article" form to have a
select field for issue_id that allows the user to select from
available issues.

In your view:

   <% form_for :article do |f| %>
      <% select :issue_id, Issue.find(:all).collect {|p| [ p.name, p.id ] } %>
      ...
   <% end %>

Then in your controller,

   @article = new Article(params[:article])
   if @article.save
       ...blah blah

This will automatically assign the article to the selected issue.

If you want to ensure that the article is linked to a valid issue, add
to your model:

   class Article < ActiveRecord::Base
     belongs_to :issue
     validates_presence_of :issue
   end