Rails 3:添加是/否“推荐”选项用户帖子的选项

发布于 2024-12-07 10:46:31 字数 321 浏览 3 评论 0原文

我是 Rails 新手,正在开发一个简单的应用程序,用户可以在其中创建包含内容的帖子,呵呵。但由于我是新人,我有些困惑。当用户创建帖子时,我希望他们有一个“推荐选项”是/否,默认为否。因此,如果用户想要推荐帖子,他只需在提交表单之前选择“是”单选按钮即可。我已经让用户和帖子模型可以创建带有标题和正文的帖子。模型关系是users has_many posts, postsoess_to user。

我想保持它非常简单,只需使用默认为“否”的“否”/“是”单选按钮向帖子模型添加一个“推荐”属性。我对 Rails 表单助手以及如何向迁移后添加是/否属性感到困惑。那么我如何选择特定@用户推荐的帖子数组呢? 多谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ゞ记忆︶ㄣ 2024-12-14 10:46:31

在迁移中:

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:(使用check_box而不是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 %>

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 %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文