我试图让所选复选框的值显示在视图中。
这是我的控制器:
class PostsController < ApplicationController
def new
end
def create
@post = Post.new(post_params)
@post.save
redirect_to @post
end
def show
@post = Post.find(params[:id])
end
def index
@posts = Post.all
end
private
def post_params
params.require(:post).permit(:check_box, :label, :id, :title, :text)
end
end
这是我的new.html.erb文件:
<h1>SWORD Mock Device Page</h1>
<%= form_for (:post), url: posts_path do |f| %>
<p>
<h2>Android Phones</h2>
<%= f.check_box(:razr_max1) %>
<%= f.label(:razr_max1, "Droid Razr Max #1") %>
</p>
<p>
<%= f.check_box(:galaxyS2) %>
<%= f.label(:galaxyS2, "Samsung Galaxy S2") %>
</p>
<p>
<h2>Android Tablets</h2>
<%= f.check_box(:asusprime3) %>
<%= f.label(:asusprime3, "Asus Transormer Prime #3") %>
</p>
<p>
<%= f.check_box(:motoxoom1) %>
<%= f.label(:motoxoom1, "Motorola Xoom #1") %>
</p>
<p>
<%=f.submit "Select" %>
</p>
<% end %>
这是我的show.html.erb文件,我想显示已检查选项的值(标签):
<p>
<strong>Device(s) chosen:</strong>
<%= @post.title %>
<%= @post.id %>
</p>
现在 - 我对ruby / rails非常新,需要一些非常可靠且解释的答案和示例。请原谅我这个非常简单和基本的问题。
非常感谢!!
ironmantis7x
答案 0 :(得分:0)
rails g model Device name category
rails g migration CreateDevicesPostsJoinTable
class CreateDevicesPostsJoinTable < ActiveRecord::Migration
def change
create_table :devices_posts, id: false do |t|
t.integer :post_id
t.integer :device_id
end
end
end
在Post模型中 has_and_belongs_to_many :devices
<h1>SWORD Mock Device Page</h1>
<%= form_for (:post), url: posts_path do |f| %>
<p>
<%=f.label :title%>
<%=f.text_field :title%>
</p>
<p>
<h2>Android Phones</h2>
<% Device.all.each do |device| %>
<div>
<%= check_box_tag "post[device_ids][]", device.id, @post.devices.include?(device) %>
<%= device.name %>
</div>
<% end %>
</p>
在帖子控制器的更新操作中def update
params[:post][:device_ids] ||= [] #to unset all the devices
#...
end
<h2> <%= @post.title %></h2>
<p>
<strong>Device(s) chosen:</strong>
<ul>
<%@post.devices.each do |device|%>
<li> <%= device.name%> </li>
<%end%>
</ul>
</p>