Search code examples
ruby-on-railsformsruby-on-rails-3.1form-helpers

Rails 3: adding a yes/no "recommended" option to user posts


I'm new to rails and I'm working on a simple app where users create posts with content, hehehe. But since I'm real new I'm having some confusion. When users create a post I want them to have a 'recommended option' yes/no which defaults on the no. So if a user wants to recommend a post he simply selects the yes radio button before he submits the form. I already have the user and post model working to create a post with a title and body. The model relationship is users has_many posts, and posts belongs_to user.

I'd like to keep it really simple and just add a 'recommended' attribute to the post model, using no/yes radio buttons which default to no. I'm confused about the rails form helpers and how to add a yes/no attribute to my post migration. Then how would I select an array of the posts which are recommended by a specific @user? Thanks a lot!


Solution

  • in the migration:

    def self.up  
      add_column :posts, :is_recommended, :boolean, :default => false  
      add_column :posts, :message, :text  
    end  
    

    posts_controller.rb:

    #rails 2 way:  
    @recommended_posts = Post.find(:all, :conditions => {:is_recommended => true, :user_id => params[:user_id]}) 
    
    #rails 3 way:  
    @recommended_posts = Post.where(:is_recommended => true, :user_id => params[:user_id]) 
    

    views/posts/new.html.erb: (using check_box rather than radio_button)

    <% form_for(@post) do |f| %>
      <p>
        <%= f.label :message %><br />
        <%= f.text_area :message %>
      </p>
      <p>
        <%= f.label 'Recommend' %><br />
        <%= f.check_box :is_recommended %>
      </p>
    <% end %>